<!doctype html><html lang=zh class=no-js> <head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><link rel="shortcut icon" href=../../assets/images/favicon.png><meta name=generator content="mkdocs-1.1.2, mkdocs-material-5.5.13"><title>MapReduce - Dayet</title><link rel=stylesheet href=../../assets/stylesheets/main.077507d7.min.css><link rel=stylesheet href=../../assets/stylesheets/palette.ff0a5ce4.min.css><meta name=theme-color content=#546d78><link href=https://fonts.gstatic.com rel=preconnect crossorigin><link rel=stylesheet href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700%7CConsolas&display=fallback"><style>body,input{font-family:"Roboto",-apple-system,BlinkMacSystemFont,Helvetica,Arial,sans-serif}code,kbd,pre{font-family:"Consolas",SFMono-Regular,Consolas,Menlo,monospace}</style><script>window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)},ga.l=+new Date,ga("create","UA-XXXXXXXX-X","auto"),ga("set","anonymizeIp",!0),ga("send","pageview"),document.addEventListener("DOMContentLoaded",function(){document.forms.search&&document.forms.search.query.addEventListener("blur",function(){if(this.value){var e=document.location.pathname;ga("send","pageview",e+"?q="+this.value)}})}),document.addEventListener("DOMContentSwitch",function(){ga("send","pageview",document.location.pathname)})</script><script async src=https://www.google-analytics.com/analytics.js></script></head> <body dir=ltr data-md-color-scheme data-md-color-primary=blue-grey data-md-color-accent=blue-grey> <input class=md-toggle data-md-toggle=drawer type=checkbox id=__drawer autocomplete=off> <input class=md-toggle data-md-toggle=search type=checkbox id=__search autocomplete=off> <label class=md-overlay for=__drawer></label> <div data-md-component=skip> <a href=#mapreduce class=md-skip> 跳转至 </a> </div> <div data-md-component=announce> </div> <header class=md-header data-md-component=header> <nav class="md-header-nav md-grid" aria-label=Header> <a href=../.. title=Dayet class="md-header-nav__button md-logo" aria-label=Dayet> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a3 3 0 003-3 3 3 0 00-3-3 3 3 0 00-3 3 3 3 0 003 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54z"/></svg> </a> <label class="md-header-nav__button md-icon" for=__drawer> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M3 6h18v2H3V6m0 5h18v2H3v-2m0 5h18v2H3v-2z"/></svg> </label> <div class=md-header-nav__title data-md-component=header-title> <div class=md-header-nav__ellipsis> <span class="md-header-nav__topic md-ellipsis"> Dayet </span> <span class="md-header-nav__topic md-ellipsis"> MapReduce </span> </div> </div> <label class="md-header-nav__button md-icon" for=__search> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0116 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.516 6.516 0 019.5 16 6.5 6.5 0 013 9.5 6.5 6.5 0 019.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5z"/></svg> </label> <div class=md-search data-md-component=search role=dialog> <label class=md-search__overlay for=__search></label> <div class=md-search__inner role=search> <form class=md-search__form name=search> <input type=text class=md-search__input name=query aria-label=搜索 placeholder=搜索 autocapitalize=off autocorrect=off autocomplete=off spellcheck=false data-md-component=search-query data-md-state=active> <label class="md-search__icon md-icon" for=__search> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M9.5 3A6.5 6.5 0 0116 9.5c0 1.61-.59 3.09-1.56 4.23l.27.27h.79l5 5-1.5 1.5-5-5v-.79l-.27-.27A6.516 6.516 0 019.5 16 6.5 6.5 0 013 9.5 6.5 6.5 0 019.5 3m0 2C7 5 5 7 5 9.5S7 14 9.5 14 14 12 14 9.5 12 5 9.5 5z"/></svg> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg> </label> <button type=reset class="md-search__icon md-icon" aria-label=Clear data-md-component=search-reset tabindex=-1> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg> </button> </form> <div class=md-search__output> <div class=md-search__scrollwrap data-md-scrollfix> <div class=md-search-result data-md-component=search-result> <div class=md-search-result__meta> Initializing search </div> <ol class=md-search-result__list></ol> </div> </div> </div> </div> </div> <div class=md-header-nav__source> <a href=https://chokgit.gitee.io/blog title="前往 GitHub 仓库" class=md-source> <div class="md-source__icon md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 448 512"><path d="M439.55 236.05L244 40.45a28.87 28.87 0 00-40.81 0l-40.66 40.63 51.52 51.52c27.06-9.14 52.68 16.77 43.39 43.68l49.66 49.66c34.23-11.8 61.18 31 35.47 56.69-26.49 26.49-70.21-2.87-56-37.34L240.22 199v121.85c25.3 12.54 22.26 41.85 9.08 55a34.34 34.34 0 01-48.55 0c-17.57-17.6-11.07-46.91 11.25-56v-123c-20.8-8.51-24.6-30.74-18.64-45L142.57 101 8.45 235.14a28.86 28.86 0 000 40.81l195.61 195.6a28.86 28.86 0 0040.8 0l194.69-194.69a28.86 28.86 0 000-40.81z"/></svg> </div> <div class=md-source__repository> 吾生也有崖，而知也无涯。 </div> </a> </div> </nav> </header> <div class=md-container data-md-component=container> <main class=md-main data-md-component=main> <div class="md-main__inner md-grid"> <div class="md-sidebar md-sidebar--primary" data-md-component=navigation> <div class=md-sidebar__scrollwrap> <div class=md-sidebar__inner> <nav class="md-nav md-nav--primary" aria-label=Navigation data-md-level=0> <label class=md-nav__title for=__drawer> <a href=../.. title=Dayet class="md-nav__button md-logo" aria-label=Dayet> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M12 8a3 3 0 003-3 3 3 0 00-3-3 3 3 0 00-3 3 3 3 0 003 3m0 3.54C9.64 9.35 6.5 8 3 8v11c3.5 0 6.64 1.35 9 3.54 2.36-2.19 5.5-3.54 9-3.54V8c-3.5 0-6.64 1.35-9 3.54z"/></svg> </a> Dayet </label> <div class=md-nav__source> <a href=https://chokgit.gitee.io/blog title="前往 GitHub 仓库" class=md-source> <div class="md-source__icon md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 448 512"><path d="M439.55 236.05L244 40.45a28.87 28.87 0 00-40.81 0l-40.66 40.63 51.52 51.52c27.06-9.14 52.68 16.77 43.39 43.68l49.66 49.66c34.23-11.8 61.18 31 35.47 56.69-26.49 26.49-70.21-2.87-56-37.34L240.22 199v121.85c25.3 12.54 22.26 41.85 9.08 55a34.34 34.34 0 01-48.55 0c-17.57-17.6-11.07-46.91 11.25-56v-123c-20.8-8.51-24.6-30.74-18.64-45L142.57 101 8.45 235.14a28.86 28.86 0 000 40.81l195.61 195.6a28.86 28.86 0 0040.8 0l194.69-194.69a28.86 28.86 0 000-40.81z"/></svg> </div> <div class=md-source__repository> 吾生也有崖，而知也无涯。 </div> </a> </div> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../.. title=主页 class=md-nav__link> 主页 </a> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-2 type=checkbox id=nav-2> <label class=md-nav__link for=nav-2> 系统基础 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=系统基础 data-md-level=1> <label class=md-nav__title for=nav-2> <span class="md-nav__icon md-icon"></span> 系统基础 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E7%B3%BB%E7%BB%9F/Linux/ title=Linux class=md-nav__link> Linux </a> </li> <li class=md-nav__item> <a href=../../%E7%B3%BB%E7%BB%9F/Shell/ title=Shell class=md-nav__link> Shell </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-3 type=checkbox id=nav-3> <label class=md-nav__link for=nav-3> 编程语言 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=编程语言 data-md-level=1> <label class=md-nav__title for=nav-3> <span class="md-nav__icon md-icon"></span> 编程语言 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E5%BF%85%E5%A4%87%E6%8A%80%E6%9C%AF/JavaSE/ title=Java class=md-nav__link> Java </a> </li> <li class=md-nav__item> <a href=../../%E5%BF%85%E5%A4%87%E6%8A%80%E6%9C%AF/Scala/ title=Scala class=md-nav__link> Scala </a> </li> <li class=md-nav__item> <a href=../../%E5%BF%85%E5%A4%87%E6%8A%80%E6%9C%AF/Python/ title=Python class=md-nav__link> Python </a> </li> <li class=md-nav__item> <a href=../../%E5%BF%85%E5%A4%87%E6%8A%80%E6%9C%AF/Kotlin/ title=Kotlin class=md-nav__link> Kotlin </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-4 type=checkbox id=nav-4> <label class=md-nav__link for=nav-4> 前端技术 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=前端技术 data-md-level=1> <label class=md-nav__title for=nav-4> <span class="md-nav__icon md-icon"></span> 前端技术 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E5%89%8D%E7%AB%AF/Vue/ title=Vue class=md-nav__link> Vue </a> </li> <li class=md-nav__item> <a href=../../%E5%89%8D%E7%AB%AF/Element-UI/ title=Element-UI-admin class=md-nav__link> Element-UI-admin </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-5 type=checkbox id=nav-5> <label class=md-nav__link for=nav-5> 后端技术 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=后端技术 data-md-level=1> <label class=md-nav__title for=nav-5> <span class="md-nav__icon md-icon"></span> 后端技术 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E5%90%8E%E7%AB%AF/SpringBoot/ title=SpringBoot class=md-nav__link> SpringBoot </a> </li> <li class=md-nav__item> <a href=../../%E5%90%8E%E7%AB%AF/Mybatis/ title=Mybatis class=md-nav__link> Mybatis </a> </li> <li class=md-nav__item> <a href=../../%E5%90%8E%E7%AB%AF/SpringData/ title=SpringData class=md-nav__link> SpringData </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-6 type=checkbox id=nav-6> <label class=md-nav__link for=nav-6> 中间件 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=中间件 data-md-level=1> <label class=md-nav__title for=nav-6> <span class="md-nav__icon md-icon"></span> 中间件 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E4%B8%AD%E9%97%B4%E4%BB%B6/Nginx/ title=Nginx class=md-nav__link> Nginx </a> </li> <li class=md-nav__item> <a href=../../%E4%B8%AD%E9%97%B4%E4%BB%B6/Tomcat/ title=Tomcat class=md-nav__link> Tomcat </a> </li> <li class=md-nav__item> <a href=../../%E4%B8%AD%E9%97%B4%E4%BB%B6/RabbitMQ/ title=RabbitMQ class=md-nav__link> RabbitMQ </a> </li> <li class=md-nav__item> <a href=../../%E4%B8%AD%E9%97%B4%E4%BB%B6/RocketMQ/ title=RocketMQ class=md-nav__link> RocketMQ </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--active md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-7 type=checkbox id=nav-7 checked> <label class=md-nav__link for=nav-7> 大数据 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=大数据 data-md-level=1> <label class=md-nav__title for=nav-7> <span class="md-nav__icon md-icon"></span> 大数据 </label> <ul class=md-nav__list data-md-scrollfix> <li class="md-nav__item md-nav__item--active md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-7-1 type=checkbox id=nav-7-1 checked> <label class=md-nav__link for=nav-7-1> Hadoop <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=Hadoop data-md-level=2> <label class=md-nav__title for=nav-7-1> <span class="md-nav__icon md-icon"></span> Hadoop </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../Hadoop%E5%9F%BA%E7%A1%80/ title=入门 class=md-nav__link> 入门 </a> </li> <li class=md-nav__item> <a href=../Hadoop-HDFS/ title=HDFS class=md-nav__link> HDFS </a> </li> <li class="md-nav__item md-nav__item--active"> <input class="md-nav__toggle md-toggle" data-md-toggle=toc type=checkbox id=__toc> <label class="md-nav__link md-nav__link--active" for=__toc> MapReduce <span class="md-nav__icon md-icon"></span> </label> <a href=./ title=MapReduce class="md-nav__link md-nav__link--active"> MapReduce </a> <nav class="md-nav md-nav--secondary" aria-label=目录> <label class=md-nav__title for=__toc> <span class="md-nav__icon md-icon"></span> 目录 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=#1-mapreduce class=md-nav__link> 第1章 MapReduce概述 </a> </li> <li class=md-nav__item> <a href=#11-mapreduce class=md-nav__link> 1.1 MapReduce定义 </a> </li> <li class=md-nav__item> <a href=#12-mapreduce class=md-nav__link> 1.2 MapReduce优缺点 </a> <nav class=md-nav aria-label="1.2 MapReduce优缺点"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#121 class=md-nav__link> 1.2.1 优点 </a> </li> <li class=md-nav__item> <a href=#122 class=md-nav__link> 1.2.2 缺点 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#13-mapreduce class=md-nav__link> 1.3 MapReduce核心思想 </a> </li> <li class=md-nav__item> <a href=#14-mapreduce class=md-nav__link> 1.4 MapReduce进程 </a> </li> <li class=md-nav__item> <a href=#15-wordcount class=md-nav__link> 1.5 官方WordCount源码 </a> </li> <li class=md-nav__item> <a href=#16 class=md-nav__link> 1.6 常用数据序列化类型 </a> </li> <li class=md-nav__item> <a href=#17-mapreduce class=md-nav__link> 1.7 MapReduce编程规范 </a> </li> <li class=md-nav__item> <a href=#18-wordcount class=md-nav__link> 1.8 WordCount案例实操 </a> </li> <li class=md-nav__item> <a href=#2-hadoop class=md-nav__link> 第2章 Hadoop序列化 </a> </li> <li class=md-nav__item> <a href=#21 class=md-nav__link> 2.1 序列化概述 </a> </li> <li class=md-nav__item> <a href=#22-beanwritable class=md-nav__link> 2.2 自定义bean对象实现序列化接口（Writable） </a> </li> <li class=md-nav__item> <a href=#23 class=md-nav__link> 2.3 序列化案例实操 </a> </li> <li class=md-nav__item> <a href=#3-mapreduce class=md-nav__link> 第3章 MapReduce框架原理 </a> </li> <li class=md-nav__item> <a href=#31-inputformat class=md-nav__link> 3.1 InputFormat数据输入 </a> <nav class=md-nav aria-label="3.1 InputFormat数据输入"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#311-maptask class=md-nav__link> 3.1.1 切片与MapTask并行度决定机制 </a> </li> <li class=md-nav__item> <a href=#312-job class=md-nav__link> 3.1.2 Job提交流程源码和切片源码详解 </a> </li> <li class=md-nav__item> <a href=#313-fileinputformat class=md-nav__link> 3.1.3 FileInputFormat切片机制 </a> </li> <li class=md-nav__item> <a href=#314-combinetextinputformat class=md-nav__link> 3.1.4 CombineTextInputFormat切片机制 </a> </li> <li class=md-nav__item> <a href=#315-combinetextinputformat class=md-nav__link> 3.1.5 CombineTextInputFormat案例实操 </a> </li> <li class=md-nav__item> <a href=#316-fileinputformat class=md-nav__link> 3.1.6 FileInputFormat实现类 </a> </li> <li class=md-nav__item> <a href=#317-keyvaluetextinputformat class=md-nav__link> 3.1.7 KeyValueTextInputFormat使用案例 </a> </li> <li class=md-nav__item> <a href=#318-nlineinputformat class=md-nav__link> 3.1.8 NLineInputFormat使用案例 </a> </li> <li class=md-nav__item> <a href=#319-inputformat class=md-nav__link> 3.1.9 自定义InputFormat </a> </li> <li class=md-nav__item> <a href=#3110-inputformat class=md-nav__link> 3.1.10 自定义InputFormat案例实操 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#32-mapreduce class=md-nav__link> 3.2 MapReduce工作流程 </a> </li> <li class=md-nav__item> <a href=#33-shuffle class=md-nav__link> 3.3 Shuffle机制 </a> <nav class=md-nav aria-label="3.3 Shuffle机制"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#331-shuffle class=md-nav__link> 3.3.1 Shuffle机制 </a> </li> <li class=md-nav__item> <a href=#332-partition class=md-nav__link> 3.3.2 Partition分区 </a> </li> <li class=md-nav__item> <a href=#333-partition class=md-nav__link> 3.3.3 Partition分区案例实操 </a> </li> <li class=md-nav__item> <a href=#334-writablecomparable class=md-nav__link> 3.3.4 WritableComparable排序 </a> </li> <li class=md-nav__item> <a href=#335-writablecomparable class=md-nav__link> 3.3.5 WritableComparable排序案例实操（全排序） </a> </li> <li class=md-nav__item> <a href=#336-writablecomparable class=md-nav__link> 3.3.6 WritableComparable排序案例实操（区内排序） </a> </li> <li class=md-nav__item> <a href=#337-combiner class=md-nav__link> 3.3.7 Combiner合并 </a> </li> <li class=md-nav__item> <a href=#338-combiner class=md-nav__link> 3.3.8 Combiner合并案例实操 </a> </li> <li class=md-nav__item> <a href=#339-groupingcomparator class=md-nav__link> 3.3.9 GroupingComparator分组（辅助排序） </a> </li> <li class=md-nav__item> <a href=#3310-groupingcomparator class=md-nav__link> 3.3.10 GroupingComparator分组案例实操 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#34-maptask class=md-nav__link> 3.4 MapTask工作机制 </a> </li> <li class=md-nav__item> <a href=#35-reducetask class=md-nav__link> 3.5 ReduceTask工作机制 </a> </li> <li class=md-nav__item> <a href=#36-outputformat class=md-nav__link> 3.6 OutputFormat数据输出 </a> <nav class=md-nav aria-label="3.6 OutputFormat数据输出"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#361-outputformat class=md-nav__link> 3.6.1 OutputFormat接口实现类 </a> </li> <li class=md-nav__item> <a href=#362-outputformat class=md-nav__link> 3.6.2 自定义OutputFormat </a> </li> <li class=md-nav__item> <a href=#363-outputformat class=md-nav__link> 3.6.3 自定义OutputFormat案例实操 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#37-join class=md-nav__link> 3.7 Join多种应用 </a> <nav class=md-nav aria-label="3.7 Join多种应用"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#371-reduce-join class=md-nav__link> 3.7.1 Reduce Join </a> </li> <li class=md-nav__item> <a href=#372-reduce-join class=md-nav__link> 3.7.2 Reduce Join案例实操 </a> </li> <li class=md-nav__item> <a href=#373-map-join class=md-nav__link> 3.7.3 Map Join </a> </li> <li class=md-nav__item> <a href=#374-map-join class=md-nav__link> 3.7.4 Map Join案例实操 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#38 class=md-nav__link> 3.8 计数器应用 </a> </li> <li class=md-nav__item> <a href=#39-etl class=md-nav__link> 3.9 数据清洗（ETL） </a> <nav class=md-nav aria-label="3.9 数据清洗（ETL）"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#391- class=md-nav__link> 3.9.1 数据清洗案例实操-简单解析版 </a> </li> <li class=md-nav__item> <a href=#392- class=md-nav__link> 3.9.2 数据清洗案例实操-复杂解析版 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#310-mapreduce class=md-nav__link> 3.10 MapReduce开发总结 </a> </li> <li class=md-nav__item> <a href=#4-hadoop class=md-nav__link> 第4章 Hadoop数据压缩 </a> </li> <li class=md-nav__item> <a href=#41 class=md-nav__link> 4.1 概述 </a> </li> <li class=md-nav__item> <a href=#42-mr class=md-nav__link> 4.2 MR支持的压缩编码 </a> </li> <li class=md-nav__item> <a href=#43 class=md-nav__link> 4.3 压缩方式选择 </a> <nav class=md-nav aria-label="4.3 压缩方式选择"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#431-gzip class=md-nav__link> 4.3.1 Gzip压缩 </a> </li> <li class=md-nav__item> <a href=#432-bzip2 class=md-nav__link> 4.3.2 Bzip2压缩 </a> </li> <li class=md-nav__item> <a href=#433-lzo class=md-nav__link> 4.3.3 Lzo压缩 </a> </li> <li class=md-nav__item> <a href=#434-snappy class=md-nav__link> 4.3.4 Snappy压缩 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#44 class=md-nav__link> 4.4 压缩位置选择 </a> </li> <li class=md-nav__item> <a href=#45 class=md-nav__link> 4.5 压缩参数配置 </a> </li> <li class=md-nav__item> <a href=#46 class=md-nav__link> 4.6 压缩实操案例 </a> <nav class=md-nav aria-label="4.6 压缩实操案例"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#461 class=md-nav__link> 4.6.1 数据流的压缩和解压缩 </a> </li> <li class=md-nav__item> <a href=#462-map class=md-nav__link> 4.6.2 Map输出端采用压缩 </a> </li> <li class=md-nav__item> <a href=#463-reduce class=md-nav__link> 4.6.3 Reduce输出端采用压缩 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#5-yarn class=md-nav__link> 第5章 Yarn资源调度器 </a> </li> <li class=md-nav__item> <a href=#51-yarn class=md-nav__link> 5.1 Yarn基本架构 </a> </li> <li class=md-nav__item> <a href=#53-yarn class=md-nav__link> 5.3 Yarn工作机制 </a> </li> <li class=md-nav__item> <a href=#54 class=md-nav__link> 5.4 作业提交全过程 </a> </li> <li class=md-nav__item> <a href=#55 class=md-nav__link> 5.5 资源调度器 </a> </li> <li class=md-nav__item> <a href=#56 class=md-nav__link> 5.6 任务的推测执行 </a> </li> <li class=md-nav__item> <a href=#6-hadoop class=md-nav__link> 第6章 Hadoop企业优化 </a> </li> <li class=md-nav__item> <a href=#61-mapreduce class=md-nav__link> 6.1 MapReduce 跑的慢的原因 </a> </li> <li class=md-nav__item> <a href=#62-mapreduce class=md-nav__link> 6.2 MapReduce优化方法 </a> <nav class=md-nav aria-label="6.2 MapReduce优化方法"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#621 class=md-nav__link> 6.2.1 数据输入 </a> </li> <li class=md-nav__item> <a href=#622-map class=md-nav__link> 6.2.2 Map阶段 </a> </li> <li class=md-nav__item> <a href=#623-reduce class=md-nav__link> 6.2.3 Reduce阶段 </a> </li> <li class=md-nav__item> <a href=#624-io class=md-nav__link> 6.2.4 I/O传输 </a> </li> <li class=md-nav__item> <a href=#625 class=md-nav__link> 6.2.5 数据倾斜问题 </a> </li> <li class=md-nav__item> <a href=#626 class=md-nav__link> 6.2.6 常用的调优参数 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#63-hdfs class=md-nav__link> 6.3 HDFS小文件优化方法 </a> <nav class=md-nav aria-label="6.3 HDFS小文件优化方法"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#631-hdfs class=md-nav__link> 6.3.1 HDFS小文件弊端 </a> </li> <li class=md-nav__item> <a href=#632-hdfs class=md-nav__link> 6.3.2 HDFS小文件解决方案 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#7-mapreduce class=md-nav__link> 第7章 MapReduce扩展案例 </a> </li> <li class=md-nav__item> <a href=#71-job class=md-nav__link> 7.1 倒排索引案例（多job串联） </a> </li> <li class=md-nav__item> <a href=#72-topn class=md-nav__link> 7.2 TopN案例 </a> </li> <li class=md-nav__item> <a href=#73 class=md-nav__link> 7.3 找博客共同好友案例 </a> </li> <li class=md-nav__item> <a href=#8 class=md-nav__link> 第8章 常见错误及解决方案 </a> </li> </ul> </nav> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-7-2 type=checkbox id=nav-7-2> <label class=md-nav__link for=nav-7-2> Spark <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=Spark data-md-level=2> <label class=md-nav__title for=nav-7-2> <span class="md-nav__icon md-icon"></span> Spark </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../Spark%E5%9F%BA%E7%A1%80/ title=Spark基础 class=md-nav__link> Spark基础 </a> </li> <li class=md-nav__item> <a href=../SparkCore/ title=SparkCore class=md-nav__link> SparkCore </a> </li> <li class=md-nav__item> <a href=../SparkSql/ title=SparkSql class=md-nav__link> SparkSql </a> </li> <li class=md-nav__item> <a href=../SparkStreaming/ title=SparkStreaming class=md-nav__link> SparkStreaming </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=../Flink/ title=Flink class=md-nav__link> Flink </a> </li> <li class=md-nav__item> <a href=../Zookeeper/ title=Zookeeper class=md-nav__link> Zookeeper </a> </li> <li class=md-nav__item> <a href=../Hbase/ title=HBase class=md-nav__link> HBase </a> </li> <li class=md-nav__item> <a href=../Hive/ title=Hive class=md-nav__link> Hive </a> </li> <li class=md-nav__item> <a href=../Kafka/ title=Kafka class=md-nav__link> Kafka </a> </li> <li class=md-nav__item> <a href=../Flume/ title=Flume class=md-nav__link> Flume </a> </li> <li class=md-nav__item> <a href=../Sqoop/ title=Sqoop class=md-nav__link> Sqoop </a> </li> <li class=md-nav__item> <a href=../Oozie/ title=Oozie class=md-nav__link> Oozie </a> </li> <li class=md-nav__item> <a href=../Azkaban/ title=Azkaban class=md-nav__link> Azkaban </a> </li> <li class=md-nav__item> <a href=../Kylin/ title=Kylin class=md-nav__link> Kylin </a> </li> <li class=md-nav__item> <a href=../Presto/ title=Presto class=md-nav__link> Presto </a> </li> <li class=md-nav__item> <a href=../ELK/ title=ELK class=md-nav__link> ELK </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-8 type=checkbox id=nav-8> <label class=md-nav__link for=nav-8> 数据库 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=数据库 data-md-level=1> <label class=md-nav__title for=nav-8> <span class="md-nav__icon md-icon"></span> 数据库 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E5%BF%85%E5%A4%87%E6%8A%80%E6%9C%AF/Mysql%E5%AE%89%E8%A3%85/ title=Mysql安装 class=md-nav__link> Mysql安装 </a> </li> <li class=md-nav__item> <a href=../../%E5%BF%85%E5%A4%87%E6%8A%80%E6%9C%AF/Oracle%E5%AE%89%E8%A3%85/ title=Oracle安装 class=md-nav__link> Oracle安装 </a> </li> <li class=md-nav__item> <a href=../../%E5%BF%85%E5%A4%87%E6%8A%80%E6%9C%AF/Redis%E5%AE%89%E8%A3%85/ title=Redis安装 class=md-nav__link> Redis安装 </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-9 type=checkbox id=nav-9> <label class=md-nav__link for=nav-9> 项目开发 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=项目开发 data-md-level=1> <label class=md-nav__title for=nav-9> <span class="md-nav__icon md-icon"></span> 项目开发 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E9%A1%B9%E7%9B%AE%E5%BC%80%E5%8F%91/Web%E5%BC%80%E5%8F%91/ title=Web开发 class=md-nav__link> Web开发 </a> </li> <li class=md-nav__item> <a href=../../%E9%A1%B9%E7%9B%AE%E5%BC%80%E5%8F%91/%E5%AE%89%E5%8D%93%E5%BC%80%E5%8F%91/ title=安卓开发 class=md-nav__link> 安卓开发 </a> </li> <li class=md-nav__item> <a href=../../%E9%A1%B9%E7%9B%AE%E5%BC%80%E5%8F%91/PC%E7%AB%AF%E5%BC%80%E5%8F%91/ title=PC端开发 class=md-nav__link> PC端开发 </a> </li> <li class=md-nav__item> <a href=../../%E9%A1%B9%E7%9B%AE%E5%BC%80%E5%8F%91/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%BC%80%E5%8F%91/ title=大数据开发 class=md-nav__link> 大数据开发 </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-10 type=checkbox id=nav-10> <label class=md-nav__link for=nav-10> 必备技能 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=必备技能 data-md-level=1> <label class=md-nav__title for=nav-10> <span class="md-nav__icon md-icon"></span> 必备技能 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E5%BF%85%E5%A4%87%E6%8A%80%E6%9C%AF/Git/ title=Git class=md-nav__link> Git </a> </li> <li class=md-nav__item> <a href=../../%E5%BF%85%E5%A4%87%E6%8A%80%E6%9C%AF/Zabbix5/ title=Zabbix class=md-nav__link> Zabbix </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-11 type=checkbox id=nav-11> <label class=md-nav__link for=nav-11> 常用工具 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=常用工具 data-md-level=1> <label class=md-nav__title for=nav-11> <span class="md-nav__icon md-icon"></span> 常用工具 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/IDEA/ title=IDEA class=md-nav__link> IDEA </a> </li> <li class=md-nav__item> <a href=../../%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/Wiki/ title=Wiki class=md-nav__link> Wiki </a> </li> </ul> </nav> </li> <li class="md-nav__item md-nav__item--nested"> <input class="md-nav__toggle md-toggle" data-md-toggle=nav-12 type=checkbox id=nav-12> <label class=md-nav__link for=nav-12> 面试题库 <span class="md-nav__icon md-icon"></span> </label> <nav class=md-nav aria-label=面试题库 data-md-level=1> <label class=md-nav__title for=nav-12> <span class="md-nav__icon md-icon"></span> 面试题库 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=../../%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/IDEA/ title=编程语言 class=md-nav__link> 编程语言 </a> </li> <li class=md-nav__item> <a href=../../%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/IDEA/ title=系统操作 class=md-nav__link> 系统操作 </a> </li> <li class=md-nav__item> <a href=../../%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/IDEA/ title=数据库 class=md-nav__link> 数据库 </a> </li> <li class=md-nav__item> <a href=../../%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/IDEA/ title=大数据 class=md-nav__link> 大数据 </a> </li> <li class=md-nav__item> <a href=../../%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7/IDEA/ title=项目 class=md-nav__link> 项目 </a> </li> </ul> </nav> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component=toc> <div class=md-sidebar__scrollwrap> <div class=md-sidebar__inner> <nav class="md-nav md-nav--secondary" aria-label=目录> <label class=md-nav__title for=__toc> <span class="md-nav__icon md-icon"></span> 目录 </label> <ul class=md-nav__list data-md-scrollfix> <li class=md-nav__item> <a href=#1-mapreduce class=md-nav__link> 第1章 MapReduce概述 </a> </li> <li class=md-nav__item> <a href=#11-mapreduce class=md-nav__link> 1.1 MapReduce定义 </a> </li> <li class=md-nav__item> <a href=#12-mapreduce class=md-nav__link> 1.2 MapReduce优缺点 </a> <nav class=md-nav aria-label="1.2 MapReduce优缺点"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#121 class=md-nav__link> 1.2.1 优点 </a> </li> <li class=md-nav__item> <a href=#122 class=md-nav__link> 1.2.2 缺点 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#13-mapreduce class=md-nav__link> 1.3 MapReduce核心思想 </a> </li> <li class=md-nav__item> <a href=#14-mapreduce class=md-nav__link> 1.4 MapReduce进程 </a> </li> <li class=md-nav__item> <a href=#15-wordcount class=md-nav__link> 1.5 官方WordCount源码 </a> </li> <li class=md-nav__item> <a href=#16 class=md-nav__link> 1.6 常用数据序列化类型 </a> </li> <li class=md-nav__item> <a href=#17-mapreduce class=md-nav__link> 1.7 MapReduce编程规范 </a> </li> <li class=md-nav__item> <a href=#18-wordcount class=md-nav__link> 1.8 WordCount案例实操 </a> </li> <li class=md-nav__item> <a href=#2-hadoop class=md-nav__link> 第2章 Hadoop序列化 </a> </li> <li class=md-nav__item> <a href=#21 class=md-nav__link> 2.1 序列化概述 </a> </li> <li class=md-nav__item> <a href=#22-beanwritable class=md-nav__link> 2.2 自定义bean对象实现序列化接口（Writable） </a> </li> <li class=md-nav__item> <a href=#23 class=md-nav__link> 2.3 序列化案例实操 </a> </li> <li class=md-nav__item> <a href=#3-mapreduce class=md-nav__link> 第3章 MapReduce框架原理 </a> </li> <li class=md-nav__item> <a href=#31-inputformat class=md-nav__link> 3.1 InputFormat数据输入 </a> <nav class=md-nav aria-label="3.1 InputFormat数据输入"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#311-maptask class=md-nav__link> 3.1.1 切片与MapTask并行度决定机制 </a> </li> <li class=md-nav__item> <a href=#312-job class=md-nav__link> 3.1.2 Job提交流程源码和切片源码详解 </a> </li> <li class=md-nav__item> <a href=#313-fileinputformat class=md-nav__link> 3.1.3 FileInputFormat切片机制 </a> </li> <li class=md-nav__item> <a href=#314-combinetextinputformat class=md-nav__link> 3.1.4 CombineTextInputFormat切片机制 </a> </li> <li class=md-nav__item> <a href=#315-combinetextinputformat class=md-nav__link> 3.1.5 CombineTextInputFormat案例实操 </a> </li> <li class=md-nav__item> <a href=#316-fileinputformat class=md-nav__link> 3.1.6 FileInputFormat实现类 </a> </li> <li class=md-nav__item> <a href=#317-keyvaluetextinputformat class=md-nav__link> 3.1.7 KeyValueTextInputFormat使用案例 </a> </li> <li class=md-nav__item> <a href=#318-nlineinputformat class=md-nav__link> 3.1.8 NLineInputFormat使用案例 </a> </li> <li class=md-nav__item> <a href=#319-inputformat class=md-nav__link> 3.1.9 自定义InputFormat </a> </li> <li class=md-nav__item> <a href=#3110-inputformat class=md-nav__link> 3.1.10 自定义InputFormat案例实操 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#32-mapreduce class=md-nav__link> 3.2 MapReduce工作流程 </a> </li> <li class=md-nav__item> <a href=#33-shuffle class=md-nav__link> 3.3 Shuffle机制 </a> <nav class=md-nav aria-label="3.3 Shuffle机制"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#331-shuffle class=md-nav__link> 3.3.1 Shuffle机制 </a> </li> <li class=md-nav__item> <a href=#332-partition class=md-nav__link> 3.3.2 Partition分区 </a> </li> <li class=md-nav__item> <a href=#333-partition class=md-nav__link> 3.3.3 Partition分区案例实操 </a> </li> <li class=md-nav__item> <a href=#334-writablecomparable class=md-nav__link> 3.3.4 WritableComparable排序 </a> </li> <li class=md-nav__item> <a href=#335-writablecomparable class=md-nav__link> 3.3.5 WritableComparable排序案例实操（全排序） </a> </li> <li class=md-nav__item> <a href=#336-writablecomparable class=md-nav__link> 3.3.6 WritableComparable排序案例实操（区内排序） </a> </li> <li class=md-nav__item> <a href=#337-combiner class=md-nav__link> 3.3.7 Combiner合并 </a> </li> <li class=md-nav__item> <a href=#338-combiner class=md-nav__link> 3.3.8 Combiner合并案例实操 </a> </li> <li class=md-nav__item> <a href=#339-groupingcomparator class=md-nav__link> 3.3.9 GroupingComparator分组（辅助排序） </a> </li> <li class=md-nav__item> <a href=#3310-groupingcomparator class=md-nav__link> 3.3.10 GroupingComparator分组案例实操 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#34-maptask class=md-nav__link> 3.4 MapTask工作机制 </a> </li> <li class=md-nav__item> <a href=#35-reducetask class=md-nav__link> 3.5 ReduceTask工作机制 </a> </li> <li class=md-nav__item> <a href=#36-outputformat class=md-nav__link> 3.6 OutputFormat数据输出 </a> <nav class=md-nav aria-label="3.6 OutputFormat数据输出"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#361-outputformat class=md-nav__link> 3.6.1 OutputFormat接口实现类 </a> </li> <li class=md-nav__item> <a href=#362-outputformat class=md-nav__link> 3.6.2 自定义OutputFormat </a> </li> <li class=md-nav__item> <a href=#363-outputformat class=md-nav__link> 3.6.3 自定义OutputFormat案例实操 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#37-join class=md-nav__link> 3.7 Join多种应用 </a> <nav class=md-nav aria-label="3.7 Join多种应用"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#371-reduce-join class=md-nav__link> 3.7.1 Reduce Join </a> </li> <li class=md-nav__item> <a href=#372-reduce-join class=md-nav__link> 3.7.2 Reduce Join案例实操 </a> </li> <li class=md-nav__item> <a href=#373-map-join class=md-nav__link> 3.7.3 Map Join </a> </li> <li class=md-nav__item> <a href=#374-map-join class=md-nav__link> 3.7.4 Map Join案例实操 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#38 class=md-nav__link> 3.8 计数器应用 </a> </li> <li class=md-nav__item> <a href=#39-etl class=md-nav__link> 3.9 数据清洗（ETL） </a> <nav class=md-nav aria-label="3.9 数据清洗（ETL）"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#391- class=md-nav__link> 3.9.1 数据清洗案例实操-简单解析版 </a> </li> <li class=md-nav__item> <a href=#392- class=md-nav__link> 3.9.2 数据清洗案例实操-复杂解析版 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#310-mapreduce class=md-nav__link> 3.10 MapReduce开发总结 </a> </li> <li class=md-nav__item> <a href=#4-hadoop class=md-nav__link> 第4章 Hadoop数据压缩 </a> </li> <li class=md-nav__item> <a href=#41 class=md-nav__link> 4.1 概述 </a> </li> <li class=md-nav__item> <a href=#42-mr class=md-nav__link> 4.2 MR支持的压缩编码 </a> </li> <li class=md-nav__item> <a href=#43 class=md-nav__link> 4.3 压缩方式选择 </a> <nav class=md-nav aria-label="4.3 压缩方式选择"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#431-gzip class=md-nav__link> 4.3.1 Gzip压缩 </a> </li> <li class=md-nav__item> <a href=#432-bzip2 class=md-nav__link> 4.3.2 Bzip2压缩 </a> </li> <li class=md-nav__item> <a href=#433-lzo class=md-nav__link> 4.3.3 Lzo压缩 </a> </li> <li class=md-nav__item> <a href=#434-snappy class=md-nav__link> 4.3.4 Snappy压缩 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#44 class=md-nav__link> 4.4 压缩位置选择 </a> </li> <li class=md-nav__item> <a href=#45 class=md-nav__link> 4.5 压缩参数配置 </a> </li> <li class=md-nav__item> <a href=#46 class=md-nav__link> 4.6 压缩实操案例 </a> <nav class=md-nav aria-label="4.6 压缩实操案例"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#461 class=md-nav__link> 4.6.1 数据流的压缩和解压缩 </a> </li> <li class=md-nav__item> <a href=#462-map class=md-nav__link> 4.6.2 Map输出端采用压缩 </a> </li> <li class=md-nav__item> <a href=#463-reduce class=md-nav__link> 4.6.3 Reduce输出端采用压缩 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#5-yarn class=md-nav__link> 第5章 Yarn资源调度器 </a> </li> <li class=md-nav__item> <a href=#51-yarn class=md-nav__link> 5.1 Yarn基本架构 </a> </li> <li class=md-nav__item> <a href=#53-yarn class=md-nav__link> 5.3 Yarn工作机制 </a> </li> <li class=md-nav__item> <a href=#54 class=md-nav__link> 5.4 作业提交全过程 </a> </li> <li class=md-nav__item> <a href=#55 class=md-nav__link> 5.5 资源调度器 </a> </li> <li class=md-nav__item> <a href=#56 class=md-nav__link> 5.6 任务的推测执行 </a> </li> <li class=md-nav__item> <a href=#6-hadoop class=md-nav__link> 第6章 Hadoop企业优化 </a> </li> <li class=md-nav__item> <a href=#61-mapreduce class=md-nav__link> 6.1 MapReduce 跑的慢的原因 </a> </li> <li class=md-nav__item> <a href=#62-mapreduce class=md-nav__link> 6.2 MapReduce优化方法 </a> <nav class=md-nav aria-label="6.2 MapReduce优化方法"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#621 class=md-nav__link> 6.2.1 数据输入 </a> </li> <li class=md-nav__item> <a href=#622-map class=md-nav__link> 6.2.2 Map阶段 </a> </li> <li class=md-nav__item> <a href=#623-reduce class=md-nav__link> 6.2.3 Reduce阶段 </a> </li> <li class=md-nav__item> <a href=#624-io class=md-nav__link> 6.2.4 I/O传输 </a> </li> <li class=md-nav__item> <a href=#625 class=md-nav__link> 6.2.5 数据倾斜问题 </a> </li> <li class=md-nav__item> <a href=#626 class=md-nav__link> 6.2.6 常用的调优参数 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#63-hdfs class=md-nav__link> 6.3 HDFS小文件优化方法 </a> <nav class=md-nav aria-label="6.3 HDFS小文件优化方法"> <ul class=md-nav__list> <li class=md-nav__item> <a href=#631-hdfs class=md-nav__link> 6.3.1 HDFS小文件弊端 </a> </li> <li class=md-nav__item> <a href=#632-hdfs class=md-nav__link> 6.3.2 HDFS小文件解决方案 </a> </li> </ul> </nav> </li> <li class=md-nav__item> <a href=#7-mapreduce class=md-nav__link> 第7章 MapReduce扩展案例 </a> </li> <li class=md-nav__item> <a href=#71-job class=md-nav__link> 7.1 倒排索引案例（多job串联） </a> </li> <li class=md-nav__item> <a href=#72-topn class=md-nav__link> 7.2 TopN案例 </a> </li> <li class=md-nav__item> <a href=#73 class=md-nav__link> 7.3 找博客共同好友案例 </a> </li> <li class=md-nav__item> <a href=#8 class=md-nav__link> 第8章 常见错误及解决方案 </a> </li> </ul> </nav> </div> </div> </div> <div class=md-content> <article class="md-content__inner md-typeset"> <h1 id=mapreduce><center>MapReduce</center></h1> <h2 id=1-mapreduce>第1章 MapReduce概述</h2> <h2 id=11-mapreduce>1.1 MapReduce定义</h2> <h2 id=12-mapreduce>1.2 MapReduce优缺点</h2> <h3 id=121>1.2.1 优点</h3> <h3 id=122>1.2.2 缺点</h3> <h2 id=13-mapreduce>1.3 MapReduce核心思想</h2> <p>MapReduce核心编程思想，如图4-1所示。</p> <p>图4-1 MapReduce核心编程思想</p> <p>1）分布式的运算程序往往需要分成至少2个阶段。</p> <p>2）第一个阶段的MapTask并发实例，完全并行运行，互不相干。</p> <p>3）第二个阶段的ReduceTask并发实例互不相干，但是他们的数据依赖于上一个阶段的所有MapTask并发实例的输出。</p> <p>4）MapReduce编程模型只能包含一个Map阶段和一个Reduce阶段，如果用户的业务逻辑非常复杂，那就只能多个MapReduce程序，串行运行。</p> <p>总结：分析WordCount数据流走向深入理解MapReduce核心思想。</p> <h2 id=14-mapreduce>1.4 MapReduce进程</h2> <h2 id=15-wordcount>1.5 官方WordCount源码</h2> <p>采用反编译工具反编译源码，发现WordCount案例有Map类、Reduce类和驱动类。且数据的类型是Hadoop自身封装的序列化类型。</p> <h2 id=16>1.6 常用数据序列化类型</h2> <p>表4-1 常用的数据类型对应的Hadoop数据序列化类型</p> <table> <thead> <tr> <th><strong>Java类型</strong></th> <th><strong>Hadoop Writable类型</strong></th> </tr> </thead> <tbody> <tr> <td>boolean</td> <td>BooleanWritable</td> </tr> <tr> <td>byte</td> <td>ByteWritable</td> </tr> <tr> <td>int</td> <td>IntWritable</td> </tr> <tr> <td>float</td> <td>FloatWritable</td> </tr> <tr> <td>long</td> <td>LongWritable</td> </tr> <tr> <td>double</td> <td>DoubleWritable</td> </tr> <tr> <td>String</td> <td>Text</td> </tr> <tr> <td>map</td> <td>MapWritable</td> </tr> <tr> <td>array</td> <td>ArrayWritable</td> </tr> </tbody> </table> <h2 id=17-mapreduce>1.7 MapReduce编程规范</h2> <p>用户编写的程序分成三个部分：Mapper、Reducer和Driver。</p> <h2 id=18-wordcount>1.8 WordCount案例实操</h2> <p>1．需求</p> <p>在给定的文本文件中统计输出每一个单词出现的总次数</p> <p>（1）输入数据</p> <p>（2）期望输出数据</p> <blockquote> <p>atguigu 2</p> <p>banzhang 1</p> <p>cls 2</p> <p>hadoop 1</p> <p>jiao 1</p> <p>ss 2</p> <p>xue 1</p> </blockquote> <p>2．需求分析</p> <p>按照MapReduce编程规范，分别编写Mapper，Reducer，Driver，如图4-2所示。</p> <p>图4-2 需求分析</p> <p>3．环境准备</p> <p>（1）创建maven工程</p> <p><img alt src=d9fe74541ebf21086b46bd7fd61426d6.png></p> <p><img alt src=3c6cdb2d60834970fbc7e529f2995dc8.png></p> <p><img alt src=c14dc880ef5bdef5b31717c17420a7ee.png></p> <p><img alt src=a1dbd504c3b9acff9e0e4035628b08c5.png></p> <p>（2）在pom.xml文件中添加如下依赖</p> <blockquote> <p>\&lt;dependencies></p> <p>\&lt;dependency></p> <p>\&lt;groupId>junit\&lt;/groupId></p> <p>\&lt;artifactId>junit\&lt;/artifactId></p> <p>\&lt;version>RELEASE\&lt;/version></p> <p>\&lt;/dependency></p> <p>\&lt;dependency></p> <p>\&lt;groupId>org.apache.logging.log4j\&lt;/groupId></p> <p>\&lt;artifactId>log4j-core\&lt;/artifactId></p> <p>\&lt;version>2.8.2\&lt;/version></p> <p>\&lt;/dependency></p> <p>\&lt;dependency></p> <p>\&lt;groupId>org.apache.hadoop\&lt;/groupId></p> <p>\&lt;artifactId>hadoop-common\&lt;/artifactId></p> <p>\&lt;version>2.7.2\&lt;/version></p> <p>\&lt;/dependency></p> <p>\&lt;dependency></p> <p>\&lt;groupId>org.apache.hadoop\&lt;/groupId></p> <p>\&lt;artifactId>hadoop-client\&lt;/artifactId></p> <p>\&lt;version>2.7.2\&lt;/version></p> <p>\&lt;/dependency></p> <p>\&lt;dependency></p> <p>\&lt;groupId>org.apache.hadoop\&lt;/groupId></p> <p>\&lt;artifactId>hadoop-hdfs\&lt;/artifactId></p> <p>\&lt;version>2.7.2\&lt;/version></p> <p>\&lt;/dependency></p> <p>\&lt;/dependencies></p> </blockquote> <p>（2）在项目的src/main/resources目录下，新建一个文件，命名为“log4j.properties”，在文件中填入。</p> <table> <thead> <tr> <th>log4j.rootLogger=INFO, stdout</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>log4j.appender.stdout=org.apache.log4j.ConsoleAppender</p> <p>log4j.appender.stdout.layout=org.apache.log4j.PatternLayout</p> <p>log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n</p> <p>log4j.appender.logfile=org.apache.log4j.FileAppender</p> <p>log4j.appender.logfile.File=target/spring.log</p> <p>log4j.appender.logfile.layout=org.apache.log4j.PatternLayout</p> <p>log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n</p> </blockquote> <p>4．编写程序</p> <p>（1）编写Mapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.IntWritable;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class WordcountMapper extends Mapper\&lt;LongWritable, Text, Text, IntWritable>{</p> <p>Text k = new Text();</p> <p>IntWritable v = new IntWritable(1);</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取一行</p> <p>String line = value.toString();</p> <p>// 2 切割</p> <p>String[] words = line.split(&rdquo; &ldquo;);</p> <p>// 3 输出</p> <p>for (String word : words) {</p> <p>k.set(word);</p> <p>context.write(k, v);</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写Reducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.wordcount;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.IntWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class WordcountReducer extends Reducer\&lt;Text, IntWritable, Text, IntWritable>{</p> <p>int sum;</p> <p>IntWritable v = new IntWritable();</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;IntWritable> values,Context context) throws IOException, InterruptedException {</p> <p>// 1 累加求和</p> <p>sum = 0;</p> <p>for (IntWritable count : values) {</p> <p>sum += count.get();</p> <p>}</p> <p>// 2 输出</p> <p>v.set(sum);</p> <p>context.write(key,v);</p> <p>}</p> <p>}</p> </blockquote> <p>（3）编写Driver驱动类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.wordcount;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.IntWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class WordcountDriver {</p> <p>public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {</p> <p>// 1 获取配置信息以及封装任务</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 2 设置jar加载路径</p> <p>job.setJarByClass(WordcountDriver.class);</p> <p>// 3 设置map和reduce类</p> <p>job.setMapperClass(WordcountMapper.class);</p> <p>job.setReducerClass(WordcountReducer.class);</p> <p>// 4 设置map输出</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(IntWritable.class);</p> <p>// 5 设置最终输出kv类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(IntWritable.class);</p> <p>// 6 设置输入和输出路径</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 7 提交</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <p>5．本地测试</p> <p>（1）如果电脑系统是win7的就将win7的hadoop jar包解压到非中文路径，并在Windows环境上配置HADOOP_HOME环境变量。如果是电脑win10操作系统，就解压win10的hadoop jar包，并配置HADOOP_HOME环境变量。</p> <p>注意：win8电脑和win10家庭版操作系统可能有问题，需要重新编译源码或者更改操作系统。</p> <p><img alt src=a6468870f38526107901f988e7484e2d.png></p> <p>（2）在Eclipse/Idea上运行程序</p> <p>6．集群上测试</p> <p>（0）用maven打jar包，需要添加的打包插件依赖</p> <p>注意：标记红颜色的部分需要替换为自己工程主类</p> <blockquote> <p>\&lt;build></p> <p>\&lt;plugins></p> <p>\&lt;plugin></p> <p>\&lt;artifactId>maven-compiler-plugin\&lt;/artifactId></p> <p>\&lt;version>2.3.2\&lt;/version></p> <p>\&lt;configuration></p> <p>\&lt;source>1.8\&lt;/source></p> <p>\&lt;target>1.8\&lt;/target></p> <p>\&lt;/configuration></p> <p>\&lt;/plugin></p> <p>\&lt;plugin></p> <p>\&lt;artifactId>maven-assembly-plugin \&lt;/artifactId></p> <p>\&lt;configuration></p> <p>\&lt;descriptorRefs></p> <p>\&lt;descriptorRef>jar-with-dependencies\&lt;/descriptorRef></p> <p>\&lt;/descriptorRefs></p> <p>\&lt;archive></p> <p>\&lt;manifest></p> <p>\&lt;mainClass>com.atguigu.mr.WordcountDriver\&lt;/mainClass></p> <p>\&lt;/manifest></p> <p>\&lt;/archive></p> <p>\&lt;/configuration></p> <p>\&lt;executions></p> <p>\&lt;execution></p> <p>\&lt;id>make-assembly\&lt;/id></p> <p>\&lt;phase>package\&lt;/phase></p> <p>\&lt;goals></p> <p>\&lt;goal>single\&lt;/goal></p> <p>\&lt;/goals></p> <p>\&lt;/execution></p> <p>\&lt;/executions></p> <p>\&lt;/plugin></p> <p>\&lt;/plugins></p> <p>\&lt;/build></p> </blockquote> <p>注意：如果工程上显示红叉。在项目上右键->maven->update project即可。</p> <p>（1）将程序打成jar包，然后拷贝到Hadoop集群中</p> <p>步骤详情：右键->Run as->maven install。等待编译完成就会在项目的target文件夹中生成jar包。如果看不到。在项目上右键-》Refresh，即可看到。修改不带依赖的jar包名称为wc.jar，并拷贝该jar包到Hadoop集群。</p> <p>（2）启动Hadoop集群</p> <p>（3）执行WordCount程序</p> <blockquote> <p>[atguigu\@hadoop102 software]$ hadoop jar wc.jar</p> <p>com.atguigu.mr.WordcountDriver /user/atguigu/input /user/atguigu/output</p> </blockquote> <p>注意：com.atguigu.mr.WordcountDriver要和自己工程的全类名一致</p> <h2 id=2-hadoop>第2章 Hadoop序列化</h2> <h2 id=21>2.1 序列化概述</h2> <h2 id=22-beanwritable>2.2 自定义bean对象实现序列化接口（Writable）</h2> <p>在企业开发中往往常用的基本序列化类型不能满足所有需求，比如在Hadoop框架内部传递一个bean对象，那么该对象就需要实现序列化接口。</p> <p>具体实现bean对象序列化步骤如下7步。</p> <blockquote> <p>（1）必须实现Writable接口</p> <p>（2）反序列化时，需要反射调用空参构造函数，所以必须有空参构造</p> </blockquote> <table> <thead> <tr> <th>public FlowBean() { super(); }</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>（3）重写序列化方法</p> </blockquote> <table> <thead> <tr> <th>\@Override public void write(DataOutput out) throws IOException { out.writeLong(upFlow); out.writeLong(downFlow); out.writeLong(sumFlow); }</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>（4）重写反序列化方法</p> </blockquote> <table> <thead> <tr> <th>\@Override public void readFields(DataInput in) throws IOException { upFlow = in.readLong(); downFlow = in.readLong(); sumFlow = in.readLong(); }</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <p>（5）注意反序列化的顺序和序列化的顺序完全一致</p> <blockquote> <p>（6）要想把结果显示在文件中，需要重写toString()，可用”\t”分开，方便后续用。</p> <p>（7）如果需要将自定义的bean放在key中传输，则还需要实现Comparable接口，因为MapReduce框中的Shuffle过程要求对key必须能排序。详见后面排序案例。</p> </blockquote> <table> <thead> <tr> <th>\@Override public int compareTo(FlowBean o) { // 倒序排列，从大到小 return this.sumFlow > o.getSumFlow() ? -1 : 1; }</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <h2 id=23>2.3 序列化案例实操</h2> <ol> <li>需求</li> </ol> <p>统计每一个手机号耗费的总上行流量、下行流量、总流量</p> <p>（1）输入数据</p> <p>（2）输入数据格式：</p> <table> <thead> <tr> <th>7 13560436666 120.196.100.99 1116 954 200 id 手机号码 网络ip 上行流量 下行流量 网络状态码</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <p>（3）期望输出数据格式</p> <table> <thead> <tr> <th>13560436666 1116 954 2070 手机号码 上行流量 下行流量 总流量</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <p>2．需求分析</p> <p>3．编写MapReduce程序</p> <blockquote> <p>（1）编写流量统计的Bean对象</p> </blockquote> <table> <thead> <tr> <th>package com.atguigu.mapreduce.flowsum;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.DataInput;</p> <p>import java.io.DataOutput;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.Writable;</p> <p>// 1 实现writable接口</p> <p>public class FlowBean implements Writable{</p> <p>private long upFlow;</p> <p>private long downFlow;</p> <p>private long sumFlow;</p> <p>//2 反序列化时，需要反射调用空参构造函数，所以必须有</p> <p>public FlowBean() {</p> <p>super();</p> <p>}</p> <p>public FlowBean(long upFlow, long downFlow) {</p> <p>super();</p> <p>this.upFlow = upFlow;</p> <p>this.downFlow = downFlow;</p> <p>this.sumFlow = upFlow + downFlow;</p> <p>}</p> <p>//3 写序列化方法</p> <p>\@Override</p> <p>public void write(DataOutput out) throws IOException {</p> <p>out.writeLong(upFlow);</p> <p>out.writeLong(downFlow);</p> <p>out.writeLong(sumFlow);</p> <p>}</p> <p>//4 反序列化方法</p> <p>//5 反序列化方法读顺序必须和写序列化方法的写顺序必须一致</p> <p>\@Override</p> <p>public void readFields(DataInput in) throws IOException {</p> <p>this.upFlow = in.readLong();</p> <p>this.downFlow = in.readLong();</p> <p>this.sumFlow = in.readLong();</p> <p>}</p> <p>// 6 编写toString方法，方便后续打印到文本</p> <p>\@Override</p> <p>public String toString() {</p> <p>return upFlow + &ldquo;\t&rdquo; + downFlow + &ldquo;\t&rdquo; + sumFlow;</p> <p>}</p> <p>public long getUpFlow() {</p> <p>return upFlow;</p> <p>}</p> <p>public void setUpFlow(long upFlow) {</p> <p>this.upFlow = upFlow;</p> <p>}</p> <p>public long getDownFlow() {</p> <p>return downFlow;</p> <p>}</p> <p>public void setDownFlow(long downFlow) {</p> <p>this.downFlow = downFlow;</p> <p>}</p> <p>public long getSumFlow() {</p> <p>return sumFlow;</p> <p>}</p> <p>public void setSumFlow(long sumFlow) {</p> <p>this.sumFlow = sumFlow;</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写Mapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.flowsum;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class FlowCountMapper extends Mapper\&lt;LongWritable, Text, Text, FlowBean>{</p> <p>FlowBean v = new FlowBean();</p> <p>Text k = new Text();</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取一行</p> <p>String line = value.toString();</p> <p>// 2 切割字段</p> <p>String[] fields = line.split(&ldquo;\t&rdquo;);</p> <p>// 3 封装对象</p> <p>// 取出手机号码</p> <p>String phoneNum = fields[1];</p> <p>// 取出上行流量和下行流量</p> <p>long upFlow = Long.parseLong(fields[fields.length - 3]);</p> <p>long downFlow = Long.parseLong(fields[fields.length - 2]);</p> <p>k.set(phoneNum);</p> <p>v.set(downFlow, upFlow);</p> <p>// 4 写出</p> <p>context.write(k, v);</p> <p>}</p> <p>}</p> </blockquote> <p>（3）编写Reducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.flowsum;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class FlowCountReducer extends Reducer\&lt;Text, FlowBean, Text, FlowBean> {</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;FlowBean> values, Context context)throws IOException, InterruptedException {</p> <p>long sum_upFlow = 0;</p> <p>long sum_downFlow = 0;</p> <p>// 1 遍历所用bean，将其中的上行流量，下行流量分别累加</p> <p>for (FlowBean flowBean : values) {</p> <p>sum_upFlow += flowBean.getUpFlow();</p> <p>sum_downFlow += flowBean.getDownFlow();</p> <p>}</p> <p>// 2 封装对象</p> <p>FlowBean resultBean = new FlowBean(sum_upFlow, sum_downFlow);</p> <p>// 3 写出</p> <p>context.write(key, resultBean);</p> <p>}</p> <p>}</p> </blockquote> <p>（4）编写Driver驱动类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.flowsum;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class FlowsumDriver {</p> <p>public static void main(String[] args) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[] { &ldquo;e:/input/inputflow&rdquo;, &ldquo;e:/output1&rdquo; };</p> <p>// 1 获取配置信息，或者job对象实例</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 6 指定本程序的jar包所在的本地路径</p> <p>job.setJarByClass(FlowsumDriver.class);</p> <p>// 2 指定本业务job要使用的mapper/Reducer业务类</p> <p>job.setMapperClass(FlowCountMapper.class);</p> <p>job.setReducerClass(FlowCountReducer.class);</p> <p>// 3 指定mapper输出数据的kv类型</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(FlowBean.class);</p> <p>// 4 指定最终输出的数据的kv类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(FlowBean.class);</p> <p>// 5 指定job的输入原始文件所在目录</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 7 将job中配置的相关参数，以及job所用的java类所在的jar包， 提交给yarn去运行</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <h2 id=3-mapreduce>第3章 MapReduce框架原理</h2> <h2 id=31-inputformat>3.1 InputFormat数据输入</h2> <h3 id=311-maptask>3.1.1 切片与MapTask并行度决定机制</h3> <p>1．问题引出</p> <p>MapTask的并行度决定Map阶段的任务处理并发度，进而影响到整个Job的处理速度。</p> <p>思考：1G的数据，启动8个MapTask，可以提高集群的并发处理能力。那么1K的数据，也启动8个MapTask，会提高集群性能吗？MapTask并行任务是否越多越好呢？哪些因素影响了MapTask并行度？</p> <p><img alt src=3b04effe56b364044cb49a0754a0a6c0.png></p> <p>2．MapTask并行度决定机制</p> <p>**数据块：**Block是HDFS物理上把数据分成一块一块。</p> <p>**数据切片：**数据切片只是在逻辑上对输入进行分片，并不会在磁盘上将其切分成片进行存储。</p> <p>图4-11 MapTask并行度决定机制</p> <h3 id=312-job>3.1.2 Job提交流程源码和切片源码详解</h3> <p>1．Job提交流程源码详解，如图4-8所示</p> <blockquote> <p>waitForCompletion()</p> <p>submit();</p> <p>// 1建立连接</p> <p>connect();</p> <p>// 1）创建提交Job的代理</p> <p>new Cluster(getConfiguration());</p> <p>// （1）判断是本地yarn还是远程</p> <p>initialize(jobTrackAddr, conf);</p> <p>// 2 提交job</p> <p>submitter.submitJobInternal(Job.this, cluster)</p> <p>// 1）创建给集群提交数据的Stag路径</p> <p>Path jobStagingArea = JobSubmissionFiles.getStagingDir(cluster, conf);</p> <p>// 2）获取jobid ，并创建Job路径</p> <p>JobID jobId = submitClient.getNewJobID();</p> <p>// 3）拷贝jar包到集群</p> <p>copyAndConfigureFiles(job, submitJobDir);</p> <p>rUploader.uploadFiles(job, jobSubmitDir);</p> <p>// 4）计算切片，生成切片规划文件</p> <p>writeSplits(job, submitJobDir);</p> <p>maps = writeNewSplits(job, jobSubmitDir);</p> <p>input.getSplits(job);</p> <p>// 5）向Stag路径写XML配置文件</p> <p>writeConf(conf, submitJobFile);</p> <p>conf.writeXml(out);</p> <p>// 6）提交Job,返回提交状态</p> <p>status = submitClient.submitJob(jobId, submitJobDir.toString(), job.getCredentials());</p> </blockquote> <p>图4-8 Job提交流程源码分析</p> <p>2．FileInputFormat切片源码解析(input.getSplits(job))</p> <h3 id=313-fileinputformat>3.1.3 FileInputFormat切片机制</h3> <h3 id=314-combinetextinputformat>3.1.4 CombineTextInputFormat切片机制</h3> <p>框架默认的TextInputFormat切片机制是对任务按文件规划切片，不管文件多小，都会是一个单独的切片，都会交给一个MapTask，这样如果有大量小文件，就会产生大量的MapTask，处理效率极其低下。</p> <p>1、应用场景：</p> <p>CombineTextInputFormat用于小文件过多的场景，它可以将多个小文件从逻辑上规划到一个切片中，这样，多个小文件就可以交给一个MapTask处理。</p> <p>2、虚拟存储切片最大值设置</p> <p>CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);// 4m</p> <p>3、切片机制</p> <p>生成切片过程包括：虚拟存储过程和切片过程二部分。</p> <blockquote> <p>（1）虚拟存储过程：</p> <p>将输入目录下所有文件大小，依次和设置的setMaxInputSplitSize值比较，如果不大于设置的最大值，逻辑上划分一个块。如果输入文件大于设置的最大值且大于两倍，那么以最大值切割一块；当剩余数据大小超过设置的最大值且不大于最大值2倍，此时将文件均分成2个虚拟存储块（防止出现太小切片）。</p> <p>例如setMaxInputSplitSize值为4M，输入文件大小为8.02M，则先逻辑上分成一个4M。剩余的大小为4.02M，如果按照4M逻辑划分，就会出现0.02M的小的虚拟存储文件，所以将剩余的4.02M文件切分成（2.01M和2.01M）两个文件。</p> </blockquote> <p>（2）切片过程：</p> <blockquote> <p>（a）判断虚拟存储的文件大小是否大于setMaxInputSplitSize值，大于等于则单独形成一个切片。</p> <p>（b）如果不大于则跟下一个虚拟存储文件进行合并，共同形成一个切片。</p> <p>（c）测试举例：有4个小文件大小分别为1.7M、5.1M、3.4M以及6.8M这四个小文件，则虚拟存储之后形成6个文件块，大小分别为：</p> <p>1.7M，（2.55M、2.55M），3.4M以及（3.4M、3.4M）</p> <p>最终会形成3个切片，大小分别为：</p> <p>（1.7+2.55）M，（2.55+3.4）M，（3.4+3.4）M</p> </blockquote> <h3 id=315-combinetextinputformat>3.1.5 CombineTextInputFormat案例实操</h3> <p>1．需求</p> <p>将输入的大量小文件合并成一个切片统一处理。</p> <p>（1）输入数据</p> <blockquote> <p>准备4个小文件</p> </blockquote> <p>（2）期望</p> <blockquote> <p>期望一个切片处理4个文件</p> </blockquote> <p>2．实现过程</p> <p><strong>（1）不做任何处理，运行1.6节的WordCount案例程序，观察切片个数为4。</strong></p> <p><img alt src=5846aee802da28fde3417058bf0d3f86.png></p> <p><strong>（2）在WordcountDriver中增加如下代码，运行程序，并观察运行的切片个数为3。</strong></p> <blockquote> <p>（a）驱动类中添加代码如下：</p> <p>// 如果不设置InputFormat，它默认用的是TextInputFormat.class</p> <p>job.setInputFormatClass(CombineTextInputFormat.class);</p> <p>//虚拟存储切片最大值设置4m</p> <p>CombineTextInputFormat.setMaxInputSplitSize(job, 4194304);</p> </blockquote> <p>（b）运行如果为3个切片。</p> <p><img alt src=394aa51c240d020215c36db1379e23f0.png></p> <p><strong>（3）在WordcountDriver中增加如下代码，运行程序，并观察运行的切片个数为1。</strong></p> <p>（a）驱动中添加代码如下：</p> <blockquote> <p>// 如果不设置InputFormat，它默认用的是TextInputFormat.class</p> <p>job.setInputFormatClass(CombineTextInputFormat.class);</p> <p>//虚拟存储切片最大值设置20m</p> <p>CombineTextInputFormat.setMaxInputSplitSize(job, 20971520);</p> <p>（b）运行如果为1个切片。</p> </blockquote> <p><img alt src=5f9a886e4339d5ac52e06e7ff4488cb4.png></p> <h3 id=316-fileinputformat>3.1.6 FileInputFormat实现类</h3> <h3 id=317-keyvaluetextinputformat>3.1.7 KeyValueTextInputFormat使用案例</h3> <p>1．需求</p> <p>统计输入文件中每一行的第一个单词相同的行数。</p> <p>（1）输入数据</p> <blockquote> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> </blockquote> <p>（2）期望结果数据</p> <blockquote> <p>banzhang 2</p> <p>xihuan 2</p> </blockquote> <p>2．需求分析</p> <p>3．代码实现</p> <p>（1）编写Mapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.KeyValueTextInputFormat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class KVTextMapper extends Mapper\&lt;Text, Text, Text, LongWritable>{</p> <p>// 1 设置value</p> <p>LongWritable v = new LongWritable(1);</p> <p>\@Override</p> <p>protected void map(Text key, Text value, Context context)</p> <p>throws IOException, InterruptedException {</p> <p>// banzhang ni hao</p> <p>// 2 写出</p> <p>context.write(key, v);</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写Reducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.KeyValueTextInputFormat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class KVTextReducer extends Reducer\&lt;Text, LongWritable, Text, LongWritable>{</p> <p>LongWritable v = new LongWritable();</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;LongWritable> values, Context context) throws IOException, InterruptedException {</p> <p>long sum = 0L;</p> <p>// 1 汇总统计</p> <p>for (LongWritable value : values) {</p> <p>sum += value.get();</p> <p>}</p> <p>v.set(sum);</p> <p>// 2 输出</p> <p>context.write(key, v);</p> <p>}</p> <p>}</p> </blockquote> <p>（3）编写Driver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.keyvaleTextInputFormat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.input.KeyValueLineRecordReader;</p> <p>import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class KVTextDriver {</p> <p>public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {</p> <p>Configuration conf = new Configuration();</p> <p>// 设置切割符</p> <p>conf.set(KeyValueLineRecordReader.KEY_VALUE_SEPERATOR, &rdquo; &ldquo;);</p> <p>// 1 获取job对象</p> <p>Job job = Job.getInstance(conf);</p> <p>// 2 设置jar包位置，关联mapper和reducer</p> <p>job.setJarByClass(KVTextDriver.class);</p> <p>job.setMapperClass(KVTextMapper.class);</p> <p>job.setReducerClass(KVTextReducer.class);</p> <p>// 3 设置map输出kv类型</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(LongWritable.class);</p> <p>// 4 设置最终输出kv类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(LongWritable.class);</p> <p>// 5 设置输入输出数据路径</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>// 设置输入格式</p> <p>job.setInputFormatClass(KeyValueTextInputFormat.class);</p> <p>// 6 设置输出数据路径</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 7 提交job</p> <p>job.waitForCompletion(true);</p> <p>}</p> <p>}</p> </blockquote> <h3 id=318-nlineinputformat>3.1.8 NLineInputFormat使用案例</h3> <p>1．需求</p> <p>对每个单词进行个数统计，要求根据每个输入文件的行数来规定输出多少个切片。此案例要求每三行放入一个切片中。</p> <p>（1）输入数据</p> <blockquote> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang banzhang ni hao</p> <p>xihuan hadoop banzhang</p> </blockquote> <p>（2）期望输出数据</p> <blockquote> <p>Number of splits:4</p> </blockquote> <p>2．需求分析</p> <p>3．代码实现</p> <p>（1）编写Mapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.nline;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class NLineMapper extends Mapper\&lt;LongWritable, Text, Text, LongWritable>{</p> <p>private Text k = new Text();</p> <p>private LongWritable v = new LongWritable(1);</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取一行</p> <p>String line = value.toString();</p> <p>// 2 切割</p> <p>String[] splited = line.split(&rdquo; &ldquo;);</p> <p>// 3 循环写出</p> <p>for (int i = 0; i \&lt; splited.length; i++) {</p> <p>k.set(splited[i]);</p> <p>context.write(k, v);</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写Reducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.nline;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class NLineReducer extends Reducer\&lt;Text, LongWritable, Text, LongWritable>{</p> <p>LongWritable v = new LongWritable();</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;LongWritable> values, Context context) throws IOException, InterruptedException {</p> <p>long sum = 0l;</p> <p>// 1 汇总</p> <p>for (LongWritable value : values) {</p> <p>sum += value.get();</p> <p>}</p> <p>v.set(sum);</p> <p>// 2 输出</p> <p>context.write(key, v);</p> <p>}</p> <p>}</p> </blockquote> <p>（3）编写Driver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.nline;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import java.net.URISyntaxException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.input.NLineInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class NLineDriver {</p> <p>public static void main(String[] args) throws IOException, URISyntaxException, ClassNotFoundException, InterruptedException {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[] { &ldquo;e:/input/inputword&rdquo;, &ldquo;e:/output1&rdquo; };</p> <p>// 1 获取job对象</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 7设置每个切片InputSplit中划分三条记录</p> <p>NLineInputFormat.setNumLinesPerSplit(job, 3);</p> <p>// 8使用NLineInputFormat处理记录数</p> <p>job.setInputFormatClass(NLineInputFormat.class);</p> <p>// 2设置jar包位置，关联mapper和reducer</p> <p>job.setJarByClass(NLineDriver.class);</p> <p>job.setMapperClass(NLineMapper.class);</p> <p>job.setReducerClass(NLineReducer.class);</p> <p>// 3设置map输出kv类型</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(LongWritable.class);</p> <p>// 4设置最终输出kv类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(LongWritable.class);</p> <p>// 5设置输入输出数据路径</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 6提交job</p> <p>job.waitForCompletion(true);</p> <p>}</p> <p>}</p> </blockquote> <p>4．测试</p> <p>（1）输入数据</p> <blockquote> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang</p> <p>banzhang ni hao</p> <p>xihuan hadoop banzhang banzhang ni hao</p> <p>xihuan hadoop banzhang</p> </blockquote> <p>（2）输出结果的切片数，如图4-10所示：</p> <p><img alt src=93c29662354c9cc26cfcdf4daba2750c.png></p> <p>图4-10 输出结果的切片数</p> <h3 id=319-inputformat>3.1.9 自定义InputFormat</h3> <h3 id=3110-inputformat>3.1.10 自定义InputFormat案例实操</h3> <p>无论HDFS还是MapReduce，在处理小文件时效率都非常低，但又难免面临处理大量小文件的场景，此时，就需要有相应解决方案。可以自定义InputFormat实现小文件的合并。</p> <p>1．需求</p> <p>将多个小文件合并成一个SequenceFile文件（SequenceFile文件是Hadoop用来存储二进制形式的key-value对的文件格式），SequenceFile里面存储着多个文件，存储的形式为文件路径+名称为key，文件内容为value。</p> <p>（1）输入数据</p> <p>（2）期望输出文件格式</p> <p>2．需求分析</p> <p>3．程序实现</p> <p>（1）自定义InputFromat</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.inputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.BytesWritable;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.mapreduce.InputSplit;</p> <p>import org.apache.hadoop.mapreduce.JobContext;</p> <p>import org.apache.hadoop.mapreduce.RecordReader;</p> <p>import org.apache.hadoop.mapreduce.TaskAttemptContext;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>// 定义类继承FileInputFormat</p> <p>public class WholeFileInputformat extends FileInputFormat\&lt;Text, BytesWritable>{</p> <p>\@Override</p> <p>protected boolean isSplitable(JobContext context, Path filename) {</p> <p>return false;</p> <p>}</p> <p>\@Override</p> <p>public RecordReader\&lt;Text, BytesWritable> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {</p> <p>WholeRecordReader recordReader = new WholeRecordReader();</p> <p>recordReader.initialize(split, context);</p> <p>return recordReader;</p> <p>}</p> <p>}</p> </blockquote> <p>（2）自定义RecordReader类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.inputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.FSDataInputStream;</p> <p>import org.apache.hadoop.fs.FileSystem;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.BytesWritable;</p> <p>import org.apache.hadoop.io.IOUtils;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.mapreduce.InputSplit;</p> <p>import org.apache.hadoop.mapreduce.RecordReader;</p> <p>import org.apache.hadoop.mapreduce.TaskAttemptContext;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileSplit;</p> <p>public class WholeRecordReader extends RecordReader\&lt;Text, BytesWritable>{</p> <p>private Configuration configuration;</p> <p>private FileSplit split;</p> <p>private boolean isProgress= true;</p> <p>private BytesWritable value = new BytesWritable();</p> <p>private Text k = new Text();</p> <p>\@Override</p> <p>public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {</p> <p>this.split = (FileSplit)split;</p> <p>configuration = context.getConfiguration();</p> <p>}</p> <p>\@Override</p> <p>public boolean nextKeyValue() throws IOException, InterruptedException {</p> <p>if (isProgress) {</p> <p>// 1 定义缓存区</p> <p>byte[] contents = new byte[(int)split.getLength()];</p> <p>FileSystem fs = null;</p> <p>FSDataInputStream fis = null;</p> <p>try {</p> <p>// 2 获取文件系统</p> <p>fs = FileSystem.get(configuration);</p> <p>// 3 读取数据</p> <p>Path path = split.getPath();</p> <p>fis = fs.open(path);</p> <p>// 4 读取文件内容</p> <p>IOUtils.readFully(fis, contents, 0, contents.length);</p> <p>// 5 输出文件内容</p> <p>value.set(contents, 0, contents.length);</p> <p>// 6 获取文件路径及名称</p> <p>String name = split.getPath().toString();</p> <p>// 7 设置输出的key值</p> <p>k.set(name);</p> <p>} catch (Exception e) {</p> <p>}finally {</p> <p>IOUtils.closeStream(fis);</p> <p>}</p> <p>isProgress = false;</p> <p>return true;</p> <p>}</p> <p>return false;</p> <p>}</p> <p>\@Override</p> <p>public Text getCurrentKey() throws IOException, InterruptedException {</p> <p>return k;</p> <p>}</p> <p>\@Override</p> <p>public BytesWritable getCurrentValue() throws IOException, InterruptedException {</p> <p>return value;</p> <p>}</p> <p>\@Override</p> <p>public float getProgress() throws IOException, InterruptedException {</p> <p>return 0;</p> <p>}</p> <p>\@Override</p> <p>public void close() throws IOException {</p> <p>}</p> <p>}</p> </blockquote> <p>（3）编写SequenceFileMapper类处理流程</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.inputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.BytesWritable;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileSplit;</p> <p>public class SequenceFileMapper extends Mapper\&lt;Text, BytesWritable, Text, BytesWritable>{</p> <p>\@Override</p> <p>protected void map(Text key, BytesWritable value, Context context) throws IOException, InterruptedException {</p> <p>context.write(key, value);</p> <p>}</p> <p>}</p> </blockquote> <p>（4）编写SequenceFileReducer类处理流程</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.inputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.BytesWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class SequenceFileReducer extends Reducer\&lt;Text, BytesWritable, Text, BytesWritable> {</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;BytesWritable> values, Context context) throws IOException, InterruptedException {</p> <p>context.write(key, values.iterator().next());</p> <p>}</p> <p>}</p> </blockquote> <p>（5）编写SequenceFileDriver类处理流程</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.inputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.BytesWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;</p> <p>public class SequenceFileDriver {</p> <p>public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[] { &ldquo;e:/input/inputinputformat&rdquo;, &ldquo;e:/output1&rdquo; };</p> <p>// 1 获取job对象</p> <p>Configuration conf = new Configuration();</p> <p>Job job = Job.getInstance(conf);</p> <p>// 2 设置jar包存储位置、关联自定义的mapper和reducer</p> <p>job.setJarByClass(SequenceFileDriver.class);</p> <p>job.setMapperClass(SequenceFileMapper.class);</p> <p>job.setReducerClass(SequenceFileReducer.class);</p> <p>// 7设置输入的inputFormat</p> <p>job.setInputFormatClass(WholeFileInputformat.class);</p> <p>// 8设置输出的outputFormat</p> <p>job.setOutputFormatClass(SequenceFileOutputFormat.class);</p> <p>// 3 设置map输出端的kv类型</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(BytesWritable.class);</p> <p>// 4 设置最终输出端的kv类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(BytesWritable.class);</p> <p>// 5 设置输入输出路径</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 6 提交job</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <h2 id=32-mapreduce>3.2 MapReduce工作流程</h2> <p>1．流程示意图，如图4-6，4-7所示。</p> <p>图4-6 MapReduce详细工作流程（一）</p> <p>图4-7 MapReduce详细工作流程（二）</p> <p>2．流程详解</p> <p>上面的流程是整个MapReduce最全工作流程，但是Shuffle过程只是从第7步开始到第16步结束，具体Shuffle过程详解，如下：</p> <p>1）MapTask收集我们的map()方法输出的kv对，放到内存缓冲区中</p> <p>2）从内存缓冲区不断溢出本地磁盘文件，可能会溢出多个文件</p> <p>3）多个溢出文件会被合并成大的溢出文件</p> <p>4）在溢出过程及合并的过程中，都要调用Partitioner进行分区和针对key进行排序</p> <p>5）ReduceTask根据自己的分区号，去各个MapTask机器上取相应的结果分区数据</p> <p>6）ReduceTask会取到同一个分区的来自不同MapTask的结果文件，ReduceTask会将这些文件再进行合并（归并排序）</p> <p>7）合并成大文件后，Shuffle的过程也就结束了，后面进入ReduceTask的逻辑运算过程（从文件中取出一个一个的键值对Group，调用用户自定义的reduce()方法）</p> <p>3．注意</p> <p>Shuffle中的缓冲区大小会影响到MapReduce程序的执行效率，原则上说，缓冲区越大，磁盘io的次数越少，执行速度就越快。</p> <p>缓冲区的大小可以通过参数调整，参数：io.sort.mb默认100M。</p> <p>4．源码解析流程</p> <blockquote> <p>context.write(k, NullWritable.get());</p> <p>output.write(key, value);</p> <p>collector.collect(key, value,partitioner.getPartition(key, value, partitions));</p> <p>HashPartitioner();</p> <p>collect()</p> <p>close()</p> <p>collect.flush()</p> <p>sortAndSpill()</p> <p>sort() QuickSort</p> <p>mergeParts();</p> </blockquote> <p><img alt src=d73a654c309311c29fb4087981023ccf.png></p> <blockquote> <p>collector.close();</p> </blockquote> <h2 id=33-shuffle>3.3 Shuffle机制</h2> <h3 id=331-shuffle>3.3.1 Shuffle机制</h3> <p>Map方法之后，Reduce方法之前的数据处理过程称之为Shuffle。如图4-14所示。</p> <p>图4-14 Shuffle机制</p> <h3 id=332-partition>3.3.2 Partition分区</h3> <h3 id=333-partition>3.3.3 Partition分区案例实操</h3> <p>1．需求</p> <p>将统计结果按照手机归属地不同省份输出到不同文件中（分区）</p> <p>（1）输入数据</p> <p>（2）期望输出数据</p> <p>手机号136、137、138、139开头都分别放到一个独立的4个文件中，其他开头的放到一个文件中。</p> <p>2．需求分析</p> <p>3．在案例2.3的基础上，增加一个分区类</p> <blockquote> <p>package com.atguigu.mapreduce.flowsum;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Partitioner;</p> <p>public class ProvincePartitioner extends Partitioner\&lt;Text, FlowBean> {</p> <p>\@Override</p> <p>public int getPartition(Text key, FlowBean value, int numPartitions) {</p> <p>// 1 获取电话号码的前三位</p> <p>String preNum = key.toString().substring(0, 3);</p> <p>int partition = 4;</p> <p>// 2 判断是哪个省</p> <p>if (&ldquo;136&rdquo;.equals(preNum)) {</p> <p>partition = 0;</p> <p>}else if (&ldquo;137&rdquo;.equals(preNum)) {</p> <p>partition = 1;</p> <p>}else if (&ldquo;138&rdquo;.equals(preNum)) {</p> <p>partition = 2;</p> <p>}else if (&ldquo;139&rdquo;.equals(preNum)) {</p> <p>partition = 3;</p> <p>}</p> <p>return partition;</p> <p>}</p> <p>}</p> </blockquote> <p>4．在驱动函数中增加自定义数据分区设置和ReduceTask设置</p> <blockquote> <p>package com.atguigu.mapreduce.flowsum;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class FlowsumDriver {</p> <p>public static void main(String[] args) throws IllegalArgumentException, IOException, ClassNotFoundException, InterruptedException {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[]{&ldquo;e:/output1&rdquo;,&rdquo;e:/output2&rdquo;};</p> <p>// 1 获取配置信息，或者job对象实例</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 2 指定本程序的jar包所在的本地路径</p> <p>job.setJarByClass(FlowsumDriver.class);</p> <p>// 3 指定本业务job要使用的mapper/Reducer业务类</p> <p>job.setMapperClass(FlowCountMapper.class);</p> <p>job.setReducerClass(FlowCountReducer.class);</p> <p>// 4 指定mapper输出数据的kv类型</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(FlowBean.class);</p> <p>// 5 指定最终输出的数据的kv类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(FlowBean.class);</p> <p>// 8 指定自定义数据分区</p> <p>job.setPartitionerClass(ProvincePartitioner.class);</p> <p>// 9 同时指定相应数量的reduce task</p> <p>job.setNumReduceTasks(5);</p> <p>// 6 指定job的输入原始文件所在目录</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 7 将job中配置的相关参数，以及job所用的java类所在的jar包， 提交给yarn去运行</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <h3 id=334-writablecomparable>3.3.4 WritableComparable排序</h3> <p>1．排序的分类</p> <p>2．自定义排序WritableComparable</p> <p>（1）原理分析</p> <p>bean对象做为key传输，需要实现WritableComparable接口重写compareTo方法，就可以实现排序。</p> <blockquote> <p>\@Override</p> <p>public int compareTo(FlowBean o) {</p> <p>int result;</p> <p>// 按照总流量大小，倒序排列</p> <p>if (sumFlow > bean.getSumFlow()) {</p> <p>result = -1;</p> <p>}else if (sumFlow \&lt; bean.getSumFlow()) {</p> <p>result = 1;</p> <p>}else {</p> <p>result = 0;</p> <p>}</p> <p>return result;</p> <p>}</p> </blockquote> <h3 id=335-writablecomparable>3.3.5 WritableComparable排序案例实操（全排序）</h3> <p>1．需求</p> <p>根据案例2.3产生的结果再次对总流量进行排序。</p> <p>（1）输入数据</p> <blockquote> <p>原始数据 第一次处理后的数据</p> </blockquote> <p>（2）期望输出数据</p> <blockquote> <p>13509468723 7335 110349 117684</p> <p>13736230513 2481 24681 27162</p> <p>13956435636 132 1512 1644</p> <p>13846544121 264 0 264</p> <p>。。。 。。。</p> </blockquote> <p>2．需求分析</p> <p>3．代码实现</p> <p>（1）FlowBean对象在在需求1基础上增加了比较功能</p> <blockquote> <p>package com.atguigu.mapreduce.sort;</p> <p>import java.io.DataInput;</p> <p>import java.io.DataOutput;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.WritableComparable;</p> <p>public class FlowBean implements WritableComparable\&lt;FlowBean> {</p> <p>private long upFlow;</p> <p>private long downFlow;</p> <p>private long sumFlow;</p> <p>// 反序列化时，需要反射调用空参构造函数，所以必须有</p> <p>public FlowBean() {</p> <p>super();</p> <p>}</p> <p>public FlowBean(long upFlow, long downFlow) {</p> <p>super();</p> <p>this.upFlow = upFlow;</p> <p>this.downFlow = downFlow;</p> <p>this.sumFlow = upFlow + downFlow;</p> <p>}</p> <p>public void set(long upFlow, long downFlow) {</p> <p>this.upFlow = upFlow;</p> <p>this.downFlow = downFlow;</p> <p>this.sumFlow = upFlow + downFlow;</p> <p>}</p> <p>public long getSumFlow() {</p> <p>return sumFlow;</p> <p>}</p> <p>public void setSumFlow(long sumFlow) {</p> <p>this.sumFlow = sumFlow;</p> <p>}</p> <p>public long getUpFlow() {</p> <p>return upFlow;</p> <p>}</p> <p>public void setUpFlow(long upFlow) {</p> <p>this.upFlow = upFlow;</p> <p>}</p> <p>public long getDownFlow() {</p> <p>return downFlow;</p> <p>}</p> <p>public void setDownFlow(long downFlow) {</p> <p>this.downFlow = downFlow;</p> <p>}</p> <p>/**</p> <p>* 序列化方法</p> <p>* \@param out</p> <p>* \@throws IOException</p> <p>*/</p> <p>\@Override</p> <p>public void write(DataOutput out) throws IOException {</p> <p>out.writeLong(upFlow);</p> <p>out.writeLong(downFlow);</p> <p>out.writeLong(sumFlow);</p> <p>}</p> <p>/**</p> <p>* 反序列化方法 注意反序列化的顺序和序列化的顺序完全一致</p> <p>* \@param in</p> <p>* \@throws IOException</p> <p>*/</p> <p>\@Override</p> <p>public void readFields(DataInput in) throws IOException {</p> <p>upFlow = in.readLong();</p> <p>downFlow = in.readLong();</p> <p>sumFlow = in.readLong();</p> <p>}</p> <p>\@Override</p> <p>public String toString() {</p> <p>return upFlow + &ldquo;\t&rdquo; + downFlow + &ldquo;\t&rdquo; + sumFlow;</p> <p>}</p> <p>\@Override</p> <p>public int compareTo(FlowBean o) {</p> <p>int result;</p> <p>// 按照总流量大小，倒序排列</p> <p>if (sumFlow > bean.getSumFlow()) {</p> <p>result = -1;</p> <p>}else if (sumFlow \&lt; bean.getSumFlow()) {</p> <p>result = 1;</p> <p>}else {</p> <p>result = 0;</p> <p>}</p> <p>return result;</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写Mapper类</p> <blockquote> <p>package com.atguigu.mapreduce.sort;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class FlowCountSortMapper extends Mapper\&lt;LongWritable, Text, FlowBean, Text>{</p> <p>FlowBean bean = new FlowBean();</p> <p>Text v = new Text();</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取一行</p> <p>String line = value.toString();</p> <p>// 2 截取</p> <p>String[] fields = line.split(&ldquo;\t&rdquo;);</p> <p>// 3 封装对象</p> <p>String phoneNbr = fields[0];</p> <p>long upFlow = Long.parseLong(fields[1]);</p> <p>long downFlow = Long.parseLong(fields[2]);</p> <p>bean.set(upFlow, downFlow);</p> <p>v.set(phoneNbr);</p> <p>// 4 输出</p> <p>context.write(bean, v);</p> <p>}</p> <p>}</p> </blockquote> <p>（3）编写Reducer类</p> <blockquote> <p>package com.atguigu.mapreduce.sort;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class FlowCountSortReducer extends Reducer\&lt;FlowBean, Text, Text, FlowBean>{</p> <p>\@Override</p> <p>protected void reduce(FlowBean key, Iterable\&lt;Text> values, Context context) throws IOException, InterruptedException {</p> <p>// 循环输出，避免总流量相同情况</p> <p>for (Text value : values) {</p> <p>context.write(value, key);</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>（4）编写Driver类</p> <blockquote> <p>package com.atguigu.mapreduce.sort;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class FlowCountSortDriver {</p> <p>public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[]{&ldquo;e:/output1&rdquo;,&rdquo;e:/output2&rdquo;};</p> <p>// 1 获取配置信息，或者job对象实例</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 2 指定本程序的jar包所在的本地路径</p> <p>job.setJarByClass(FlowCountSortDriver.class);</p> <p>// 3 指定本业务job要使用的mapper/Reducer业务类</p> <p>job.setMapperClass(FlowCountSortMapper.class);</p> <p>job.setReducerClass(FlowCountSortReducer.class);</p> <p>// 4 指定mapper输出数据的kv类型</p> <p>job.setMapOutputKeyClass(FlowBean.class);</p> <p>job.setMapOutputValueClass(Text.class);</p> <p>// 5 指定最终输出的数据的kv类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(FlowBean.class);</p> <p>// 6 指定job的输入原始文件所在目录</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 7 将job中配置的相关参数，以及job所用的java类所在的jar包， 提交给yarn去运行</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <h3 id=336-writablecomparable>3.3.6 WritableComparable排序案例实操（区内排序）</h3> <p>1．需求</p> <p>要求每个省份手机号输出的文件中按照总流量内部排序。</p> <p>2．需求分析</p> <p>基于前一个需求，增加自定义分区类，分区按照省份手机号设置。</p> <p>3．案例实操</p> <p>（1）增加自定义分区类</p> <blockquote> <p>package com.atguigu.mapreduce.sort;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Partitioner;</p> <p>public class ProvincePartitioner extends Partitioner\&lt;FlowBean, Text> {</p> <p>\@Override</p> <p>public int getPartition(FlowBean key, Text value, int numPartitions) {</p> <p>// 1 获取手机号码前三位</p> <p>String preNum = value.toString().substring(0, 3);</p> <p>int partition = 4;</p> <p>// 2 根据手机号归属地设置分区</p> <p>if (&ldquo;136&rdquo;.equals(preNum)) {</p> <p>partition = 0;</p> <p>}else if (&ldquo;137&rdquo;.equals(preNum)) {</p> <p>partition = 1;</p> <p>}else if (&ldquo;138&rdquo;.equals(preNum)) {</p> <p>partition = 2;</p> <p>}else if (&ldquo;139&rdquo;.equals(preNum)) {</p> <p>partition = 3;</p> <p>}</p> <p>return partition;</p> <p>}</p> <p>}</p> </blockquote> <p>（2）在驱动类中添加分区类</p> <blockquote> <p>// 加载自定义分区类</p> <p>job.setPartitionerClass(ProvincePartitioner.class);</p> <p>// 设置Reducetask个数</p> <p>job.setNumReduceTasks(5);</p> </blockquote> <h3 id=337-combiner>3.3.7 Combiner合并</h3> <p>（6）自定义Combiner实现步骤</p> <p>（a）自定义一个Combiner继承Reducer，重写Reduce方法</p> <table> <thead> <tr> <th>public class WordcountCombiner extends Reducer\&lt;Text, IntWritable, Text, IntWritable>{ IntWritable v = new IntWritable(); \@Override protected void reduce(Text key, Iterable\&lt;IntWritable> values, Reducer\&lt;Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException { int sum = 0; // 1 汇总操作 for (IntWritable value : values) { sum += value.get(); } v.set(sum); // 2 写出 context.write(key, v); } }</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>（b）在Job驱动类中设置：</p> </blockquote> <table> <thead> <tr> <th>job.setCombinerClass(WordcountCombiner.class);</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <h3 id=338-combiner>3.3.8 Combiner合并案例实操</h3> <p>1．需求</p> <p>统计过程中对每一个MapTask的输出进行局部汇总，以减小网络传输量即采用Combiner功能。</p> <p>（1）数据输入</p> <p>（2）期望输出数据</p> <p>期望：Combine输入数据多，输出时经过合并，输出数据降低。</p> <p>2．需求分析</p> <p>图4-15 Combiner的合并案例</p> <p>3．案例实操-方案一</p> <p>1）增加一个WordcountCombiner类继承Reducer</p> <blockquote> <p>package com.atguigu.mr.combiner;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.IntWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class WordcountCombiner extends Reducer\&lt;Text, IntWritable, Text, IntWritable>{</p> <p>IntWritable v = new IntWritable();</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;IntWritable> values, Context context) throws IOException, InterruptedException {</p> <p>// 1 汇总</p> <p>int sum = 0;</p> <p>for(IntWritable value :values){</p> <p>sum += value.get();</p> <p>}</p> <p>v.set(sum);</p> <p>// 2 写出</p> <p>context.write(key, v);</p> <p>}</p> <p>}</p> </blockquote> <p>2）在WordcountDriver驱动类中指定Combiner</p> <blockquote> <p>// 指定需要使用combiner，以及用哪个类作为combiner的逻辑</p> <p>job.setCombinerClass(WordcountCombiner.class);</p> </blockquote> <p>4．案例实操-方案二</p> <p>1）将WordcountReducer作为Combiner在WordcountDriver驱动类中指定</p> <blockquote> <p>// 指定需要使用Combiner，以及用哪个类作为Combiner的逻辑</p> <p>job.setCombinerClass(WordcountReducer.class);</p> </blockquote> <p>运行程序，如图4-16，4-17所示</p> <p><img alt src=be78bdf8fd6391df12d1f2416ce19770.png></p> <p>图4-16 未使用前</p> <p><img alt src=76313eb138596214f713f05f09d8f6f3.png></p> <p>图4-17 使用后</p> <h3 id=339-groupingcomparator>3.3.9 GroupingComparator分组（辅助排序）</h3> <p>对Reduce阶段的数据根据某一个或几个字段进行分组。</p> <p>分组排序步骤：</p> <p>（1）自定义类继承WritableComparator</p> <p>（2）重写compare()方法</p> <blockquote> <p>\@Override</p> <p>public int compare(WritableComparable a, WritableComparable b) {</p> <p>// 比较的业务逻辑</p> <p>… …</p> <p>return result;</p> <p>}</p> </blockquote> <p>（3）创建一个构造将比较对象的类传给父类</p> <blockquote> <p>protected OrderGroupingComparator() {</p> <p>super(OrderBean.class, true);</p> <p>}</p> </blockquote> <h3 id=3310-groupingcomparator>3.3.10 GroupingComparator分组案例实操</h3> <p>1．需求</p> <p>有如下订单数据</p> <p>表4-2 订单数据</p> <table> <thead> <tr> <th>订单id</th> <th>商品id</th> <th>成交金额</th> </tr> </thead> <tbody> <tr> <td>0000001</td> <td>Pdt_01</td> <td>222.8</td> </tr> <tr> <td></td> <td>Pdt_02</td> <td>33.8</td> </tr> <tr> <td>0000002</td> <td>Pdt_03</td> <td>522.8</td> </tr> <tr> <td></td> <td>Pdt_04</td> <td>122.4</td> </tr> <tr> <td></td> <td>Pdt_05</td> <td>722.4</td> </tr> <tr> <td>0000003</td> <td>Pdt_06</td> <td>232.8</td> </tr> <tr> <td></td> <td>Pdt_02</td> <td>33.8</td> </tr> </tbody> </table> <p>现在需要求出每一个订单中最贵的商品。</p> <p>（1）输入数据</p> <p>（2）期望输出数据</p> <p>1 222.8</p> <p>2 722.4</p> <p>3 232.8</p> <p>2．需求分析</p> <p>（1）利用“订单id和成交金额”作为key，可以将Map阶段读取到的所有订单数据按照id升序排序，如果id相同再按照金额降序排序，发送到Reduce。</p> <p>（2）在Reduce端利用groupingComparator将订单id相同的kv聚合成组，然后取第一个即是该订单中最贵商品，如图4-18所示。</p> <p>图4-18 过程分析</p> <p>3．代码实现</p> <p>（1）定义订单信息OrderBean类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.order;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.DataInput;</p> <p>import java.io.DataOutput;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.WritableComparable;</p> <p>public class OrderBean implements WritableComparable\&lt;OrderBean> {</p> <p>private int order_id; // 订单id号</p> <p>private double price; // 价格</p> <p>public OrderBean() {</p> <p>super();</p> <p>}</p> <p>public OrderBean(int order_id, double price) {</p> <p>super();</p> <p>this.order_id = order_id;</p> <p>this.price = price;</p> <p>}</p> <p>\@Override</p> <p>public void write(DataOutput out) throws IOException {</p> <p>out.writeInt(order_id);</p> <p>out.writeDouble(price);</p> <p>}</p> <p>\@Override</p> <p>public void readFields(DataInput in) throws IOException {</p> <p>order_id = in.readInt();</p> <p>price = in.readDouble();</p> <p>}</p> <p>\@Override</p> <p>public String toString() {</p> <p>return order_id + &ldquo;\t&rdquo; + price;</p> <p>}</p> <p>public int getOrder_id() {</p> <p>return order_id;</p> <p>}</p> <p>public void setOrder_id(int order_id) {</p> <p>this.order_id = order_id;</p> <p>}</p> <p>public double getPrice() {</p> <p>return price;</p> <p>}</p> <p>public void setPrice(double price) {</p> <p>this.price = price;</p> <p>}</p> <p>// 二次排序</p> <p>\@Override</p> <p>public int compareTo(OrderBean o) {</p> <p>int result;</p> <p>if (order_id > o.getOrder_id()) {</p> <p>result = 1;</p> <p>} else if (order_id \&lt; o.getOrder_id()) {</p> <p>result = -1;</p> <p>} else {</p> <p>// 价格倒序排序</p> <p>result = price > o.getPrice() ? -1 : 1;</p> <p>}</p> <p>return result;</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写OrderSortMapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.order;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class OrderMapper extends Mapper\&lt;LongWritable, Text, OrderBean, NullWritable> {</p> <p>OrderBean k = new OrderBean();</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取一行</p> <p>String line = value.toString();</p> <p>// 2 截取</p> <p>String[] fields = line.split(&ldquo;\t&rdquo;);</p> <p>// 3 封装对象</p> <p>k.setOrder_id(Integer.parseInt(fields[0]));</p> <p>k.setPrice(Double.parseDouble(fields[2]));</p> <p>// 4 写出</p> <p>context.write(k, NullWritable.get());</p> <p>}</p> <p>}</p> </blockquote> <p>（3）编写OrderSortGroupingComparator类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.order;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import org.apache.hadoop.io.WritableComparable;</p> <p>import org.apache.hadoop.io.WritableComparator;</p> <p>public class OrderGroupingComparator extends WritableComparator {</p> <p>protected OrderGroupingComparator() {</p> <p>super(OrderBean.class, true);</p> <p>}</p> <p>\@Override</p> <p>public int compare(WritableComparable a, WritableComparable b) {</p> <p>OrderBean aBean = (OrderBean) a;</p> <p>OrderBean bBean = (OrderBean) b;</p> <p>int result;</p> <p>if (aBean.getOrder_id() > bBean.getOrder_id()) {</p> <p>result = 1;</p> <p>} else if (aBean.getOrder_id() \&lt; bBean.getOrder_id()) {</p> <p>result = -1;</p> <p>} else {</p> <p>result = 0;</p> <p>}</p> <p>return result;</p> <p>}</p> <p>}</p> </blockquote> <p>（4）编写OrderSortReducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.order;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class OrderReducer extends Reducer\&lt;OrderBean, NullWritable, OrderBean, NullWritable> {</p> <p>\@Override</p> <p>protected void reduce(OrderBean key, Iterable\&lt;NullWritable> values, Context context) throws IOException, InterruptedException {</p> <p>context.write(key, NullWritable.get());</p> <p>}</p> <p>}</p> </blockquote> <p>（5）编写OrderSortDriver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.order;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class OrderDriver {</p> <p>public static void main(String[] args) throws Exception, IOException {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[]{&ldquo;e:/input/inputorder&rdquo; , &ldquo;e:/output1&rdquo;};</p> <p>// 1 获取配置信息</p> <p>Configuration conf = new Configuration();</p> <p>Job job = Job.getInstance(conf);</p> <p>// 2 设置jar包加载路径</p> <p>job.setJarByClass(OrderDriver.class);</p> <p>// 3 加载map/reduce类</p> <p>job.setMapperClass(OrderMapper.class);</p> <p>job.setReducerClass(OrderReducer.class);</p> <p>// 4 设置map输出数据key和value类型</p> <p>job.setMapOutputKeyClass(OrderBean.class);</p> <p>job.setMapOutputValueClass(NullWritable.class);</p> <p>// 5 设置最终输出数据的key和value类型</p> <p>job.setOutputKeyClass(OrderBean.class);</p> <p>job.setOutputValueClass(NullWritable.class);</p> <p>// 6 设置输入数据和输出数据路径</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 8 设置reduce端的分组</p> <p>job.setGroupingComparatorClass(OrderGroupingComparator.class);</p> <p>// 7 提交</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <h2 id=34-maptask>3.4 MapTask工作机制</h2> <p>MapTask工作机制如图4-12所示。</p> <p>图4-12 MapTask工作机制</p> <p>（1）Read阶段：MapTask通过用户编写的RecordReader，从输入InputSplit中解析出一个个key/value。</p> <p>（2）Map阶段：该节点主要是将解析出的key/value交给用户编写map()函数处理，并产生一系列新的key/value。</p> <p>（3）Collect收集阶段：在用户编写map()函数中，当数据处理完成后，一般会调用OutputCollector.collect()输出结果。在该函数内部，它会将生成的key/value分区（调用Partitioner），并写入一个环形内存缓冲区中。</p> <p>（4）Spill阶段：即“溢写”，当环形缓冲区满后，MapReduce会将数据写到本地磁盘上，生成一个临时文件。需要注意的是，将数据写入本地磁盘之前，先要对数据进行一次本地排序，并在必要时对数据进行合并、压缩等操作。</p> <p>溢写阶段详情：</p> <p>步骤1：利用快速排序算法对缓存区内的数据进行排序，排序方式是，先按照分区编号Partition进行排序，然后按照key进行排序。这样，经过排序后，数据以分区为单位聚集在一起，且同一分区内所有数据按照key有序。</p> <p>步骤2：按照分区编号由小到大依次将每个分区中的数据写入任务工作目录下的临时文件output/spillN.out（N表示当前溢写次数）中。如果用户设置了Combiner，则写入文件之前，对每个分区中的数据进行一次聚集操作。</p> <p>步骤3：将分区数据的元信息写到内存索引数据结构SpillRecord中，其中每个分区的元信息包括在临时文件中的偏移量、压缩前数据大小和压缩后数据大小。如果当前内存索引大小超过1MB，则将内存索引写到文件output/spillN.out.index中。</p> <p>（5）Combine阶段：当所有数据处理完成后，MapTask对所有临时文件进行一次合并，以确保最终只会生成一个数据文件。</p> <p>当所有数据处理完后，MapTask会将所有临时文件合并成一个大文件，并保存到文件output/file.out中，同时生成相应的索引文件output/file.out.index。</p> <p>在进行文件合并过程中，MapTask以分区为单位进行合并。对于某个分区，它将采用多轮递归合并的方式。每轮合并io.sort.factor（默认10）个文件，并将产生的文件重新加入待合并列表中，对文件排序后，重复以上过程，直到最终得到一个大文件。</p> <p>让每个MapTask最终只生成一个数据文件，可避免同时打开大量文件和同时读取大量小文件产生的随机读取带来的开销。</p> <h2 id=35-reducetask>3.5 ReduceTask工作机制</h2> <p>1．ReduceTask工作机制</p> <p>ReduceTask工作机制，如图4-19所示。</p> <p>图4-19 ReduceTask工作机制</p> <p>（1）Copy阶段：ReduceTask从各个MapTask上远程拷贝一片数据，并针对某一片数据，如果其大小超过一定阈值，则写到磁盘上，否则直接放到内存中。</p> <p>（2）Merge阶段：在远程拷贝数据的同时，ReduceTask启动了两个后台线程对内存和磁盘上的文件进行合并，以防止内存使用过多或磁盘上文件过多。</p> <p>（3）Sort阶段：按照MapReduce语义，用户编写reduce()函数输入数据是按key进行聚集的一组数据。为了将key相同的数据聚在一起，Hadoop采用了基于排序的策略。由于各个MapTask已经实现对自己的处理结果进行了局部排序，因此，ReduceTask只需对所有数据进行一次归并排序即可。</p> <p>（4）Reduce阶段：reduce()函数将计算结果写到HDFS上。</p> <p>2．设置ReduceTask并行度（个数）</p> <p>ReduceTask的并行度同样影响整个Job的执行并发度和执行效率，但与MapTask的并发数由切片数决定不同，ReduceTask数量的决定是可以直接手动设置：</p> <blockquote> <p>// 默认值是1，手动设置为4</p> <p>job.setNumReduceTasks(4);</p> </blockquote> <p>3．实验：测试ReduceTask多少合适</p> <p>（1）实验环境：1个Master节点，16个Slave节点：CPU:8GHZ，内存: 2G</p> <p>（2）实验结论：</p> <p>表4-3 改变ReduceTask （数据量为1GB）</p> <table> <thead> <tr> <th>MapTask =16</th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>ReduceTask</td> <td>1</td> <td>5</td> <td>10</td> <td>15</td> <td>16</td> <td>20</td> <td>25</td> <td>30</td> <td>45</td> <td>60</td> </tr> <tr> <td>总时间</td> <td>892</td> <td>146</td> <td>110</td> <td>92</td> <td>88</td> <td>100</td> <td>128</td> <td>101</td> <td>145</td> <td>104</td> </tr> </tbody> </table> <p>4．注意事项</p> <h2 id=36-outputformat>3.6 OutputFormat数据输出</h2> <h3 id=361-outputformat>3.6.1 OutputFormat接口实现类</h3> <h3 id=362-outputformat>3.6.2 自定义OutputFormat</h3> <h3 id=363-outputformat>3.6.3 自定义OutputFormat案例实操</h3> <p>1．需求</p> <p>过滤输入的log日志，包含atguigu的网站输出到e:/atguigu.log，不包含atguigu的网站输出到e:/other.log。</p> <p>（1）输入数据</p> <blockquote> <p>（2）期望输出数据</p> </blockquote> <p>2．需求分析</p> <p>3．案例实操</p> <p>（1）编写FilterMapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.outputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class FilterMapper extends Mapper\&lt;LongWritable, Text, Text, NullWritable>{</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 写出</p> <p>context.write(value, NullWritable.get());</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写FilterReducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.outputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class FilterReducer extends Reducer\&lt;Text, NullWritable, Text, NullWritable> {</p> <p>Text k = new Text();</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;NullWritable> values, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取一行</p> <p>String line = key.toString();</p> <p>// 2 拼接</p> <p>line = line + &ldquo;\r\n&rdquo;;</p> <p>// 3 设置key</p> <p>k.set(line);</p> <p>// 4 输出</p> <p>context.write(k, NullWritable.get());</p> <p>}</p> <p>}</p> </blockquote> <p>（3）自定义一个OutputFormat类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.outputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.RecordWriter;</p> <p>import org.apache.hadoop.mapreduce.TaskAttemptContext;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class FilterOutputFormat extends FileOutputFormat\&lt;Text, NullWritable>{</p> <p>\@Override</p> <p>public RecordWriter\&lt;Text, NullWritable> getRecordWriter(TaskAttemptContext job) throws IOException, InterruptedException {</p> <p>// 创建一个RecordWriter</p> <p>return new FilterRecordWriter(job);</p> <p>}</p> <p>}</p> </blockquote> <p>（4）编写RecordWriter类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.outputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.fs.FSDataOutputStream;</p> <p>import org.apache.hadoop.fs.FileSystem;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.RecordWriter;</p> <p>import org.apache.hadoop.mapreduce.TaskAttemptContext;</p> <p>public class FilterRecordWriter extends RecordWriter\&lt;Text, NullWritable> {</p> <p>FSDataOutputStream atguiguOut = null;</p> <p>FSDataOutputStream otherOut = null;</p> <p>public FilterRecordWriter(TaskAttemptContext job) {</p> <p>// 1 获取文件系统</p> <p>FileSystem fs;</p> <p>try {</p> <p>fs = FileSystem.get(job.getConfiguration());</p> <p>// 2 创建输出文件路径</p> <p>Path atguiguPath = new Path(&ldquo;e:/atguigu.log&rdquo;);</p> <p>Path otherPath = new Path(&ldquo;e:/other.log&rdquo;);</p> <p>// 3 创建输出流</p> <p>atguiguOut = fs.create(atguiguPath);</p> <p>otherOut = fs.create(otherPath);</p> <p>} catch (IOException e) {</p> <p>e.printStackTrace();</p> <p>}</p> <p>}</p> <p>\@Override</p> <p>public void write(Text key, NullWritable value) throws IOException, InterruptedException {</p> <p>// 判断是否包含“atguigu”输出到不同文件</p> <p>if (key.toString().contains(&ldquo;atguigu&rdquo;)) {</p> <p>atguiguOut.write(key.toString().getBytes());</p> <p>} else {</p> <p>otherOut.write(key.toString().getBytes());</p> <p>}</p> <p>}</p> <p>\@Override</p> <p>public void close(TaskAttemptContext context) throws IOException, InterruptedException {</p> <p>// 关闭资源</p> <p>IOUtils.closeStream(atguiguOut);</p> <p>IOUtils.closeStream(otherOut);</p> <p>}</p> <p>}</p> </blockquote> <p>（5）编写FilterDriver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.outputformat;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class FilterDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[] { &ldquo;e:/input/inputoutputformat&rdquo;, &ldquo;e:/output2&rdquo; };</p> <p>Configuration conf = new Configuration();</p> <p>Job job = Job.getInstance(conf);</p> <p>job.setJarByClass(FilterDriver.class);</p> <p>job.setMapperClass(FilterMapper.class);</p> <p>job.setReducerClass(FilterReducer.class);</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(NullWritable.class);</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(NullWritable.class);</p> <p>// 要将自定义的输出格式组件设置到job中</p> <p>job.setOutputFormatClass(FilterOutputFormat.class);</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>// 虽然我们自定义了outputformat，但是因为我们的outputformat继承自fileoutputformat</p> <p>// 而fileoutputformat要输出一个_SUCCESS文件，所以，在这还得指定一个输出目录</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <h2 id=37-join>3.7 Join多种应用</h2> <h3 id=371-reduce-join>3.7.1 Reduce Join</h3> <h3 id=372-reduce-join>3.7.2 Reduce Join案例实操</h3> <p>1．需求</p> <p>表4-4 订单数据表t_order</p> <table> <thead> <tr> <th>id</th> <th>pid</th> <th>amount</th> </tr> </thead> <tbody> <tr> <td>1001</td> <td>01</td> <td>1</td> </tr> <tr> <td>1002</td> <td>02</td> <td>2</td> </tr> <tr> <td>1003</td> <td>03</td> <td>3</td> </tr> <tr> <td>1004</td> <td>01</td> <td>4</td> </tr> <tr> <td>1005</td> <td>02</td> <td>5</td> </tr> <tr> <td>1006</td> <td>03</td> <td>6</td> </tr> </tbody> </table> <p>表4-5 商品信息表t_product</p> <table> <thead> <tr> <th>pid</th> <th>pname</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>小米</td> </tr> <tr> <td>02</td> <td>华为</td> </tr> <tr> <td>03</td> <td>格力</td> </tr> </tbody> </table> <p>将商品信息表中数据根据商品pid合并到订单数据表中。</p> <p>表4-6 最终数据形式</p> <table> <thead> <tr> <th>id</th> <th>pname</th> <th>amount</th> </tr> </thead> <tbody> <tr> <td>1001</td> <td>小米</td> <td>1</td> </tr> <tr> <td>1004</td> <td>小米</td> <td>4</td> </tr> <tr> <td>1002</td> <td>华为</td> <td>2</td> </tr> <tr> <td>1005</td> <td>华为</td> <td>5</td> </tr> <tr> <td>1003</td> <td>格力</td> <td>3</td> </tr> <tr> <td>1006</td> <td>格力</td> <td>6</td> </tr> </tbody> </table> <p>2．需求分析</p> <p>通过将关联条件作为Map输出的key，将两表满足Join条件的数据并携带数据所来源的文件信息，发往同一个ReduceTask，在Reduce中进行数据的串联，如图4-20所示。</p> <p>图4-20 Reduce端表合并</p> <p>3．代码实现</p> <p>1）创建商品和订合并后的Bean类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.table;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.DataInput;</p> <p>import java.io.DataOutput;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.Writable;</p> <p>public class TableBean implements Writable {</p> <p>private String order_id; // 订单id</p> <p>private String p_id; // 产品id</p> <p>private int amount; // 产品数量</p> <p>private String pname; // 产品名称</p> <p>private String flag; // 表的标记</p> <p>public TableBean() {</p> <p>super();</p> <p>}</p> <p>public TableBean(String order_id, String p_id, int amount, String pname, String flag) {</p> <p>super();</p> <p>this.order_id = order_id;</p> <p>this.p_id = p_id;</p> <p>this.amount = amount;</p> <p>this.pname = pname;</p> <p>this.flag = flag;</p> <p>}</p> <p>public String getFlag() {</p> <p>return flag;</p> <p>}</p> <p>public void setFlag(String flag) {</p> <p>this.flag = flag;</p> <p>}</p> <p>public String getOrder_id() {</p> <p>return order_id;</p> <p>}</p> <p>public void setOrder_id(String order_id) {</p> <p>this.order_id = order_id;</p> <p>}</p> <p>public String getP_id() {</p> <p>return p_id;</p> <p>}</p> <p>public void setP_id(String p_id) {</p> <p>this.p_id = p_id;</p> <p>}</p> <p>public int getAmount() {</p> <p>return amount;</p> <p>}</p> <p>public void setAmount(int amount) {</p> <p>this.amount = amount;</p> <p>}</p> <p>public String getPname() {</p> <p>return pname;</p> <p>}</p> <p>public void setPname(String pname) {</p> <p>this.pname = pname;</p> <p>}</p> <p>\@Override</p> <p>public void write(DataOutput out) throws IOException {</p> <p>out.writeUTF(order_id);</p> <p>out.writeUTF(p_id);</p> <p>out.writeInt(amount);</p> <p>out.writeUTF(pname);</p> <p>out.writeUTF(flag);</p> <p>}</p> <p>\@Override</p> <p>public void readFields(DataInput in) throws IOException {</p> <p>this.order_id = in.readUTF();</p> <p>this.p_id = in.readUTF();</p> <p>this.amount = in.readInt();</p> <p>this.pname = in.readUTF();</p> <p>this.flag = in.readUTF();</p> <p>}</p> <p>\@Override</p> <p>public String toString() {</p> <p>return order_id + &ldquo;\t&rdquo; + pname + &ldquo;\t&rdquo; + amount + &ldquo;\t&rdquo; ;</p> <p>}</p> <p>}</p> </blockquote> <p>2）编写TableMapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.table;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileSplit;</p> <p>public class TableMapper extends Mapper\&lt;LongWritable, Text, Text, TableBean>{</p> <p>String name;</p> <p>TableBean bean = new TableBean();</p> <p>Text k = new Text();</p> <p>\@Override</p> <p>protected void setup(Context context) throws IOException, InterruptedException {</p> <p>// 1 获取输入文件切片</p> <p>FileSplit split = (FileSplit) context.getInputSplit();</p> <p>// 2 获取输入文件名称</p> <p>name = split.getPath().getName();</p> <p>}</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取输入数据</p> <p>String line = value.toString();</p> <p>// 2 不同文件分别处理</p> <p>if (name.startsWith(&ldquo;order&rdquo;)) {// 订单表处理</p> <p>// 2.1 切割</p> <p>String[] fields = line.split(&ldquo;\t&rdquo;);</p> <p>// 2.2 封装bean对象</p> <p>bean.setOrder_id(fields[0]);</p> <p>bean.setP_id(fields[1]);</p> <p>bean.setAmount(Integer.parseInt(fields[2]));</p> <p>bean.setPname(&ldquo;&rdquo;);</p> <p>bean.setFlag(&ldquo;order&rdquo;);</p> <p>k.set(fields[1]);</p> <p>}else {// 产品表处理</p> <p>// 2.3 切割</p> <p>String[] fields = line.split(&ldquo;\t&rdquo;);</p> <p>// 2.4 封装bean对象</p> <p>bean.setP_id(fields[0]);</p> <p>bean.setPname(fields[1]);</p> <p>bean.setFlag(&ldquo;pd&rdquo;);</p> <p>bean.setAmount(0);</p> <p>bean.setOrder_id(&ldquo;&rdquo;);</p> <p>k.set(fields[0]);</p> <p>}</p> <p>// 3 写出</p> <p>context.write(k, bean);</p> <p>}</p> <p>}</p> </blockquote> <p>3）编写TableReducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.table;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import java.util.ArrayList;</p> <p>import org.apache.commons.beanutils.BeanUtils;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class TableReducer extends Reducer\&lt;Text, TableBean, TableBean, NullWritable> {</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;TableBean> values, Context context) throws IOException, InterruptedException {</p> <p>// 1准备存储订单的集合</p> <p>ArrayList\&lt;TableBean> orderBeans = new ArrayList\&lt;>();</p> <p>// 2 准备bean对象</p> <p>TableBean pdBean = new TableBean();</p> <p>for (TableBean bean : values) {</p> <p>if (&ldquo;order&rdquo;.equals(bean.getFlag())) {// 订单表</p> <p>// 拷贝传递过来的每条订单数据到集合中</p> <p>TableBean orderBean = new TableBean();</p> <p>try {</p> <p>BeanUtils.copyProperties(orderBean, bean);</p> <p>} catch (Exception e) {</p> <p>e.printStackTrace();</p> <p>}</p> <p>orderBeans.add(orderBean);</p> <p>} else {// 产品表</p> <p>try {</p> <p>// 拷贝传递过来的产品表到内存中</p> <p>BeanUtils.copyProperties(pdBean, bean);</p> <p>} catch (Exception e) {</p> <p>e.printStackTrace();</p> <p>}</p> <p>}</p> <p>}</p> <p>// 3 表的拼接</p> <p>for(TableBean bean:orderBeans){</p> <p>bean.setPname (pdBean.getPname());</p> <p>// 4 数据写出去</p> <p>context.write(bean, NullWritable.get());</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>4）编写TableDriver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.table;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class TableDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>// 0 根据自己电脑路径重新配置</p> <p>args = new String[]{&ldquo;e:/input/inputtable&rdquo;,&rdquo;e:/output1&rdquo;};</p> <p>// 1 获取配置信息，或者job对象实例</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 2 指定本程序的jar包所在的本地路径</p> <p>job.setJarByClass(TableDriver.class);</p> <p>// 3 指定本业务job要使用的Mapper/Reducer业务类</p> <p>job.setMapperClass(TableMapper.class);</p> <p>job.setReducerClass(TableReducer.class);</p> <p>// 4 指定Mapper输出数据的kv类型</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(TableBean.class);</p> <p>// 5 指定最终输出的数据的kv类型</p> <p>job.setOutputKeyClass(TableBean.class);</p> <p>job.setOutputValueClass(NullWritable.class);</p> <p>// 6 指定job的输入原始文件所在目录</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 7 将job中配置的相关参数，以及job所用的java类所在的jar包， 提交给yarn去运行</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <p>4．测试</p> <p>运行程序查看结果</p> <table> <thead> <tr> <th>1001 小米 1</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>1001 小米 1</p> <p>1002 华为 2</p> <p>1002 华为 2</p> <p>1003 格力 3</p> <p>1003 格力 3</p> </blockquote> <p>5．总结</p> <h3 id=373-map-join>3.7.3 Map Join</h3> <p>1．使用场景</p> <p>Map Join适用于一张表十分小、一张表很大的场景。</p> <p>2．优点</p> <p>思考：在Reduce端处理过多的表，非常容易产生数据倾斜。怎么办？</p> <p>在Map端缓存多张表，提前处理业务逻辑，这样增加Map端业务，减少Reduce端数据的压力，尽可能的减少数据倾斜。</p> <p>3．具体办法：采用DistributedCache</p> <p>（1）在Mapper的setup阶段，将文件读取到缓存集合中。</p> <p>（2）在驱动函数中加载缓存。</p> <blockquote> <p>// 缓存普通文件到Task运行节点。</p> <p>job.addCacheFile(new URI(&ldquo;file://e:/cache/pd.txt&rdquo;));</p> </blockquote> <h3 id=374-map-join>3.7.4 Map Join案例实操</h3> <p>1．需求</p> <p>表4-4 订单数据表t_order</p> <table> <thead> <tr> <th>id</th> <th>pid</th> <th>amount</th> </tr> </thead> <tbody> <tr> <td>1001</td> <td>01</td> <td>1</td> </tr> <tr> <td>1002</td> <td>02</td> <td>2</td> </tr> <tr> <td>1003</td> <td>03</td> <td>3</td> </tr> <tr> <td>1004</td> <td>01</td> <td>4</td> </tr> <tr> <td>1005</td> <td>02</td> <td>5</td> </tr> <tr> <td>1006</td> <td>03</td> <td>6</td> </tr> </tbody> </table> <p>表4-5 商品信息表t_product</p> <table> <thead> <tr> <th>pid</th> <th>pname</th> </tr> </thead> <tbody> <tr> <td>01</td> <td>小米</td> </tr> <tr> <td>02</td> <td>华为</td> </tr> <tr> <td>03</td> <td>格力</td> </tr> </tbody> </table> <p>将商品信息表中数据根据商品pid合并到订单数据表中。</p> <p>表4-6 最终数据形式</p> <table> <thead> <tr> <th>id</th> <th>pname</th> <th>amount</th> </tr> </thead> <tbody> <tr> <td>1001</td> <td>小米</td> <td>1</td> </tr> <tr> <td>1004</td> <td>小米</td> <td>4</td> </tr> <tr> <td>1002</td> <td>华为</td> <td>2</td> </tr> <tr> <td>1005</td> <td>华为</td> <td>5</td> </tr> <tr> <td>1003</td> <td>格力</td> <td>3</td> </tr> <tr> <td>1006</td> <td>格力</td> <td>6</td> </tr> </tbody> </table> <p>2．需求分析</p> <p>MapJoin适用于关联表中有小表的情形。</p> <p>图4-21 Map端表合并</p> <p>3．实现代码</p> <p>（1）先在驱动模块中添加缓存文件</p> <table> <thead> <tr> <th>package test;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.net.URI;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class DistributedCacheDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>// 0 根据自己电脑路径重新配置</p> <p>args = new String[]{&ldquo;e:/input/inputtable2&rdquo;, &ldquo;e:/output1&rdquo;};</p> <p>// 1 获取job信息</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 2 设置加载jar包路径</p> <p>job.setJarByClass(DistributedCacheDriver.class);</p> <p>// 3 关联map</p> <p>job.setMapperClass(DistributedCacheMapper.class);</p> <p>// 4 设置最终输出数据类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(NullWritable.class);</p> <p>// 5 设置输入输出路径</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 6 加载缓存数据</p> <p>job.addCacheFile(new URI(&ldquo;file:///e:/input/inputcache/pd.txt&rdquo;));</p> <p>// 7 Map端Join的逻辑不需要Reduce阶段，设置reduceTask数量为0</p> <p>job.setNumReduceTasks(0);</p> <p>// 8 提交</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <p>（2）读取缓存的文件数据</p> <table> <thead> <tr> <th>package test;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.BufferedReader;</p> <p>import java.io.FileInputStream;</p> <p>import java.io.IOException;</p> <p>import java.io.InputStreamReader;</p> <p>import java.util.HashMap;</p> <p>import java.util.Map;</p> <p>import org.apache.commons.lang.StringUtils;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class DistributedCacheMapper extends Mapper\&lt;LongWritable, Text, Text, NullWritable>{</p> <p>Map\&lt;String, String> pdMap = new HashMap\&lt;>();</p> <p>\@Override</p> <p>protected void setup(Mapper\&lt;LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {</p> <p>// 1 获取缓存的文件</p> <p>URI[] cacheFiles = context.getCacheFiles();</p> <p>String path = cacheFiles[0].getPath().toString();</p> <p>BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), &ldquo;UTF-8&rdquo;));</p> <p>String line;</p> <p>while(StringUtils.isNotEmpty(line = reader.readLine())){</p> <p>// 2 切割</p> <p>String[] fields = line.split(&ldquo;\t&rdquo;);</p> <p>// 3 缓存数据到集合</p> <p>pdMap.put(fields[0], fields[1]);</p> <p>}</p> <p>// 4 关流</p> <p>reader.close();</p> <p>}</p> <p>Text k = new Text();</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取一行</p> <p>String line = value.toString();</p> <p>// 2 截取</p> <p>String[] fields = line.split(&ldquo;\t&rdquo;);</p> <p>// 3 获取产品id</p> <p>String pId = fields[1];</p> <p>// 4 获取商品名称</p> <p>String pdName = pdMap.get(pId);</p> <p>// 5 拼接</p> <p>k.set(line + &ldquo;\t&rdquo;+ pdName);</p> <p>// 6 写出</p> <p>context.write(k, NullWritable.get());</p> <p>}</p> <p>}</p> </blockquote> <h2 id=38>3.8 计数器应用</h2> <h2 id=39-etl>3.9 数据清洗（ETL）</h2> <p>在运行核心业务MapReduce程序之前，往往要先对数据进行清洗，清理掉不符合用户要求的数据。清理的过程往往只需要运行Mapper程序，不需要运行Reduce程序。</p> <h3 id=391->3.9.1 数据清洗案例实操-简单解析版</h3> <p>1．需求</p> <blockquote> <p>去除日志中字段长度小于等于11的日志。</p> </blockquote> <p>（1）输入数据</p> <p>（2）期望输出数据</p> <blockquote> <p>每行字段长度都大于11。</p> </blockquote> <p>2．需求分析</p> <p>需要在Map阶段对输入的数据根据规则进行过滤清洗。</p> <p>3．实现代码</p> <p>（1）编写LogMapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.weblog;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class LogMapper extends Mapper\&lt;LongWritable, Text, Text, NullWritable>{</p> <p>Text k = new Text();</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取1行数据</p> <p>String line = value.toString();</p> <p>// 2 解析日志</p> <p>boolean result = parseLog(line,context);</p> <p>// 3 日志不合法退出</p> <p>if (!result) {</p> <p>return;</p> <p>}</p> <p>// 4 设置key</p> <p>k.set(line);</p> <p>// 5 写出数据</p> <p>context.write(k, NullWritable.get());</p> <p>}</p> <p>// 2 解析日志</p> <p>private boolean parseLog(String line, Context context) {</p> <p>// 1 截取</p> <p>String[] fields = line.split(&rdquo; &ldquo;);</p> <p>// 2 日志长度大于11的为合法</p> <p>if (fields.length > 11) {</p> <p>// 系统计数器</p> <p>context.getCounter(&ldquo;map&rdquo;, &ldquo;true&rdquo;).increment(1);</p> <p>return true;</p> <p>}else {</p> <p>context.getCounter(&ldquo;map&rdquo;, &ldquo;false&rdquo;).increment(1);</p> <p>return false;</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写LogDriver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.weblog;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class LogDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[] { &ldquo;e:/input/inputlog&rdquo;, &ldquo;e:/output1&rdquo; };</p> <p>// 1 获取job信息</p> <p>Configuration conf = new Configuration();</p> <p>Job job = Job.getInstance(conf);</p> <p>// 2 加载jar包</p> <p>job.setJarByClass(LogDriver.class);</p> <p>// 3 关联map</p> <p>job.setMapperClass(LogMapper.class);</p> <p>// 4 设置最终输出类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(NullWritable.class);</p> <p>// 设置reducetask个数为0</p> <p>job.setNumReduceTasks(0);</p> <p>// 5 设置输入和输出路径</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 6 提交</p> <p>job.waitForCompletion(true);</p> <p>}</p> <p>}</p> </blockquote> <h3 id=392->3.9.2 数据清洗案例实操-复杂解析版</h3> <p>1．需求</p> <blockquote> <p>对Web访问日志中的各字段识别切分，去除日志中不合法的记录。根据清洗规则，输出过滤后的数据。</p> <p>（1）输入数据</p> <p>（2）期望输出数据</p> <p>都是合法的数据</p> </blockquote> <p>2．实现代码</p> <p>（1）定义一个bean，用来记录日志数据中的各数据字段</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.log;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>public class LogBean {</p> <p>private String remote_addr;// 记录客户端的ip地址</p> <p>private String remote_user;// 记录客户端用户名称,忽略属性&rdquo;-&ldquo;</p> <p>private String time_local;// 记录访问时间与时区</p> <p>private String request;// 记录请求的url与http协议</p> <p>private String status;// 记录请求状态；成功是200</p> <p>private String body_bytes_sent;// 记录发送给客户端文件主体内容大小</p> <p>private String http_referer;// 用来记录从那个页面链接访问过来的</p> <p>private String http_user_agent;// 记录客户浏览器的相关信息</p> <p>private boolean valid = true;// 判断数据是否合法</p> <p>public String getRemote_addr() {</p> <p>return remote_addr;</p> <p>}</p> <p>public void setRemote_addr(String remote_addr) {</p> <p>this.remote_addr = remote_addr;</p> <p>}</p> <p>public String getRemote_user() {</p> <p>return remote_user;</p> <p>}</p> <p>public void setRemote_user(String remote_user) {</p> <p>this.remote_user = remote_user;</p> <p>}</p> <p>public String getTime_local() {</p> <p>return time_local;</p> <p>}</p> <p>public void setTime_local(String time_local) {</p> <p>this.time_local = time_local;</p> <p>}</p> <p>public String getRequest() {</p> <p>return request;</p> <p>}</p> <p>public void setRequest(String request) {</p> <p>this.request = request;</p> <p>}</p> <p>public String getStatus() {</p> <p>return status;</p> <p>}</p> <p>public void setStatus(String status) {</p> <p>this.status = status;</p> <p>}</p> <p>public String getBody_bytes_sent() {</p> <p>return body_bytes_sent;</p> <p>}</p> <p>public void setBody_bytes_sent(String body_bytes_sent) {</p> <p>this.body_bytes_sent = body_bytes_sent;</p> <p>}</p> <p>public String getHttp_referer() {</p> <p>return http_referer;</p> <p>}</p> <p>public void setHttp_referer(String http_referer) {</p> <p>this.http_referer = http_referer;</p> <p>}</p> <p>public String getHttp_user_agent() {</p> <p>return http_user_agent;</p> <p>}</p> <p>public void setHttp_user_agent(String http_user_agent) {</p> <p>this.http_user_agent = http_user_agent;</p> <p>}</p> <p>public boolean isValid() {</p> <p>return valid;</p> <p>}</p> <p>public void setValid(boolean valid) {</p> <p>this.valid = valid;</p> <p>}</p> <p>\@Override</p> <p>public String toString() {</p> <p>StringBuilder sb = new StringBuilder();</p> <p>sb.append(this.valid);</p> <p>sb.append(&ldquo;\001&rdquo;).append(this.remote_addr);</p> <p>sb.append(&ldquo;\001&rdquo;).append(this.remote_user);</p> <p>sb.append(&ldquo;\001&rdquo;).append(this.time_local);</p> <p>sb.append(&ldquo;\001&rdquo;).append(this.request);</p> <p>sb.append(&ldquo;\001&rdquo;).append(this.status);</p> <p>sb.append(&ldquo;\001&rdquo;).append(this.body_bytes_sent);</p> <p>sb.append(&ldquo;\001&rdquo;).append(this.http_referer);</p> <p>sb.append(&ldquo;\001&rdquo;).append(this.http_user_agent);</p> <p>return sb.toString();</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写LogMapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.log;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class LogMapper extends Mapper\&lt;LongWritable, Text, Text, NullWritable>{</p> <p>Text k = new Text();</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取1行</p> <p>String line = value.toString();</p> <p>// 2 解析日志是否合法</p> <p>LogBean bean = parseLog(line);</p> <p>if (!bean.isValid()) {</p> <p>return;</p> <p>}</p> <p>k.set(bean.toString());</p> <p>// 3 输出</p> <p>context.write(k, NullWritable.get());</p> <p>}</p> <p>// 解析日志</p> <p>private LogBean parseLog(String line) {</p> <p>LogBean logBean = new LogBean();</p> <p>// 1 截取</p> <p>String[] fields = line.split(&rdquo; &ldquo;);</p> <p>if (fields.length > 11) {</p> <p>// 2封装数据</p> <p>logBean.setRemote_addr(fields[0]);</p> <p>logBean.setRemote_user(fields[1]);</p> <p>logBean.setTime_local(fields[3].substring(1));</p> <p>logBean.setRequest(fields[6]);</p> <p>logBean.setStatus(fields[8]);</p> <p>logBean.setBody_bytes_sent(fields[9]);</p> <p>logBean.setHttp_referer(fields[10]);</p> <p>if (fields.length > 12) {</p> <p>logBean.setHttp_user_agent(fields[11] + &rdquo; &ldquo;+ fields[12]);</p> <p>}else {</p> <p>logBean.setHttp_user_agent(fields[11]);</p> <p>}</p> <p>// 大于400，HTTP错误</p> <p>if (Integer.parseInt(logBean.getStatus()) >= 400) {</p> <p>logBean.setValid(false);</p> <p>}</p> <p>}else {</p> <p>logBean.setValid(false);</p> <p>}</p> <p>return logBean;</p> <p>}</p> <p>}</p> </blockquote> <p>（3）编写LogDriver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.log;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.NullWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class LogDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>// 1 获取job信息</p> <p>Configuration conf = new Configuration();</p> <p>Job job = Job.getInstance(conf);</p> <p>// 2 加载jar包</p> <p>job.setJarByClass(LogDriver.class);</p> <p>// 3 关联map</p> <p>job.setMapperClass(LogMapper.class);</p> <p>// 4 设置最终输出类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(NullWritable.class);</p> <p>// 5 设置输入和输出路径</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 6 提交</p> <p>job.waitForCompletion(true);</p> <p>}</p> <p>}</p> </blockquote> <h2 id=310-mapreduce>3.10 MapReduce开发总结</h2> <p>在编写MapReduce程序时，需要考虑如下几个方面：</p> <h2 id=4-hadoop>第4章 Hadoop数据压缩</h2> <h2 id=41>4.1 概述</h2> <h2 id=42-mr>4.2 MR支持的压缩编码</h2> <p>表4-7</p> <table> <thead> <tr> <th>压缩格式</th> <th>hadoop自带？</th> <th>算法</th> <th>文件扩展名</th> <th>是否可切分</th> <th>换成压缩格式后，原来的程序是否需要修改</th> </tr> </thead> <tbody> <tr> <td>DEFLATE</td> <td>是，直接使用</td> <td>DEFLATE</td> <td>.deflate</td> <td>否</td> <td>和文本处理一样，不需要修改</td> </tr> <tr> <td>Gzip</td> <td>是，直接使用</td> <td>DEFLATE</td> <td>.gz</td> <td>否</td> <td>和文本处理一样，不需要修改</td> </tr> <tr> <td>bzip2</td> <td>是，直接使用</td> <td>bzip2</td> <td>.bz2</td> <td>是</td> <td>和文本处理一样，不需要修改</td> </tr> <tr> <td>LZO</td> <td>否，需要安装</td> <td>LZO</td> <td>.lzo</td> <td>是</td> <td>需要建索引，还需要指定输入格式</td> </tr> <tr> <td>Snappy</td> <td>否，需要安装</td> <td>Snappy</td> <td>.snappy</td> <td>否</td> <td>和文本处理一样，不需要修改</td> </tr> </tbody> </table> <p>为了支持多种压缩/解压缩算法，Hadoop引入了编码/解码器，如下表所示。</p> <p>表4-8</p> <table> <thead> <tr> <th>压缩格式</th> <th>对应的编码/解码器</th> </tr> </thead> <tbody> <tr> <td>DEFLATE</td> <td>org.apache.hadoop.io.compress.DefaultCodec</td> </tr> <tr> <td>gzip</td> <td>org.apache.hadoop.io.compress.GzipCodec</td> </tr> <tr> <td>bzip2</td> <td>org.apache.hadoop.io.compress.BZip2Codec</td> </tr> <tr> <td>LZO</td> <td>com.hadoop.compression.lzo.LzopCodec</td> </tr> <tr> <td>Snappy</td> <td>org.apache.hadoop.io.compress.SnappyCodec</td> </tr> </tbody> </table> <p>压缩性能的比较</p> <p>表4-9</p> <table> <thead> <tr> <th>压缩算法</th> <th>原始文件大小</th> <th>压缩文件大小</th> <th>压缩速度</th> <th>解压速度</th> </tr> </thead> <tbody> <tr> <td>gzip</td> <td>8.3GB</td> <td>1.8GB</td> <td>17.5MB/s</td> <td>58MB/s</td> </tr> <tr> <td>bzip2</td> <td>8.3GB</td> <td>1.1GB</td> <td>2.4MB/s</td> <td>9.5MB/s</td> </tr> <tr> <td>LZO</td> <td>8.3GB</td> <td>2.9GB</td> <td>49.3MB/s</td> <td>74.6MB/s</td> </tr> </tbody> </table> <p><a href=http://google.github.io/snappy/ >http://google.github.io/snappy/</a></p> <p>On a single core of a Core i7 processor in 64-bit mode, Snappy compresses at about 250 MB/sec or more and decompresses at about 500 MB/sec or more.</p> <h2 id=43>4.3 压缩方式选择</h2> <h3 id=431-gzip>4.3.1 Gzip压缩</h3> <h3 id=432-bzip2>4.3.2 Bzip2压缩</h3> <h3 id=433-lzo>4.3.3 Lzo压缩</h3> <h3 id=434-snappy>4.3.4 Snappy压缩</h3> <h2 id=44>4.4 压缩位置选择</h2> <p>压缩可以在MapReduce作用的任意阶段启用，如图4-22所示。</p> <p>图4-22 MapReduce数据压缩</p> <h2 id=45>4.5 压缩参数配置</h2> <p>要在Hadoop中启用压缩，可以配置如下参数：</p> <p>表4-10 配置参数</p> <table> <thead> <tr> <th>参数</th> <th>默认值</th> <th>阶段</th> <th>建议</th> </tr> </thead> <tbody> <tr> <td>io.compression.codecs （在core-site.xml中配置）</td> <td>org.apache.hadoop.io.compress.DefaultCodec, org.apache.hadoop.io.compress.GzipCodec, org.apache.hadoop.io.compress.BZip2Codec</td> <td>输入压缩</td> <td>Hadoop使用文件扩展名判断是否支持某种编解码器</td> </tr> <tr> <td>mapreduce.map.output.compress（在mapred-site.xml中配置）</td> <td>false</td> <td>mapper输出</td> <td>这个参数设为true启用压缩</td> </tr> <tr> <td>mapreduce.map.output.compress.codec（在mapred-site.xml中配置）</td> <td>org.apache.hadoop.io.compress.DefaultCodec</td> <td>mapper输出</td> <td>企业多使用LZO或Snappy编解码器在此阶段压缩数据</td> </tr> <tr> <td>mapreduce.output.fileoutputformat.compress（在mapred-site.xml中配置）</td> <td>false</td> <td>reducer输出</td> <td>这个参数设为true启用压缩</td> </tr> <tr> <td>mapreduce.output.fileoutputformat.compress.codec（在mapred-site.xml中配置）</td> <td>org.apache.hadoop.io.compress. DefaultCodec</td> <td>reducer输出</td> <td>使用标准工具或者编解码器，如gzip和bzip2</td> </tr> <tr> <td>mapreduce.output.fileoutputformat.compress.type（在mapred-site.xml中配置）</td> <td>RECORD</td> <td>reducer输出</td> <td>SequenceFile输出使用的压缩类型：NONE和BLOCK</td> </tr> </tbody> </table> <h2 id=46>4.6 压缩实操案例</h2> <h3 id=461>4.6.1 数据流的压缩和解压缩</h3> <p>测试一下如下压缩方式：</p> <p>表4-11</p> <table> <thead> <tr> <th>DEFLATE</th> <th>org.apache.hadoop.io.compress.DefaultCodec</th> </tr> </thead> <tbody> <tr> <td>gzip</td> <td>org.apache.hadoop.io.compress.GzipCodec</td> </tr> <tr> <td>bzip2</td> <td>org.apache.hadoop.io.compress.BZip2Codec</td> </tr> </tbody> </table> <p>package com.atguigu.mapreduce.compress;</p> <p>import java.io.File;</p> <p>import java.io.FileInputStream;</p> <p>import java.io.FileNotFoundException;</p> <p>import java.io.FileOutputStream;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.IOUtils;</p> <p>import org.apache.hadoop.io.compress.CompressionCodec;</p> <p>import org.apache.hadoop.io.compress.CompressionCodecFactory;</p> <p>import org.apache.hadoop.io.compress.CompressionInputStream;</p> <p>import org.apache.hadoop.io.compress.CompressionOutputStream;</p> <p>import org.apache.hadoop.util.ReflectionUtils;</p> <p>public class TestCompress {</p> <p>public static void main(String[] args) throws Exception {</p> <p>compress(&ldquo;e:/hello.txt&rdquo;,&rdquo;org.apache.hadoop.io.compress.BZip2Codec&rdquo;);</p> <p>// decompress(&ldquo;e:/hello.txt.bz2&rdquo;);</p> <p>}</p> <p>// 1、压缩</p> <p>private static void compress(String filename, String method) throws Exception {</p> <p>// （1）获取输入流</p> <p>FileInputStream fis = new FileInputStream(new File(filename));</p> <p>Class codecClass = Class.forName(method);</p> <p>CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, new Configuration());</p> <p>// （2）获取输出流</p> <p>FileOutputStream fos = new FileOutputStream(new File(filename + codec.getDefaultExtension()));</p> <p>CompressionOutputStream cos = codec.createOutputStream(fos);</p> <p>// （3）流的对拷</p> <p>IOUtils.copyBytes(fis, cos, 1024*1024*5, false);</p> <p>// （4）关闭资源</p> <p>cos.close();</p> <p>fos.close();</p> <p>fis.close();</p> <p>}</p> <p>// 2、解压缩</p> <p>private static void decompress(String filename) throws FileNotFoundException, IOException {</p> <p>// （0）校验是否能解压缩</p> <p>CompressionCodecFactory factory = new CompressionCodecFactory(new Configuration());</p> <p>CompressionCodec codec = factory.getCodec(new Path(filename));</p> <p>if (codec == null) {</p> <p>System.out.println(&ldquo;cannot find codec for file &rdquo; + filename);</p> <p>return;</p> <p>}</p> <p>// （1）获取输入流</p> <p>CompressionInputStream cis = codec.createInputStream(new FileInputStream(new File(filename)));</p> <p>// （2）获取输出流</p> <p>FileOutputStream fos = new FileOutputStream(new File(filename + &ldquo;.decoded&rdquo;));</p> <p>// （3）流的对拷</p> <p>IOUtils.copyBytes(cis, fos, 1024*1024*5, false);</p> <p>// （4）关闭资源</p> <p>cis.close();</p> <p>fos.close();</p> <p>}</p> <p>}</p> <h3 id=462-map>4.6.2 Map输出端采用压缩</h3> <p>即使你的MapReduce的输入输出文件都是未压缩的文件，你仍然可以对Map任务的中间结果输出做压缩，因为它要写在硬盘并且通过网络传输到Reduce节点，对其压缩可以提高很多性能，这些工作只要设置两个属性即可，我们来看下代码怎么设置。</p> <p>1．给大家提供的Hadoop源码支持的压缩格式有：BZip2Codec 、DefaultCodec</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.compress; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.BZip2Codec; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class WordCountDriver { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { Configuration configuration = new Configuration(); // 开启map端输出压缩 configuration.setBoolean(&ldquo;mapreduce.map.output.compress&rdquo;, true); // 设置map端输出压缩方式 configuration.setClass(&ldquo;mapreduce.map.output.compress.codec&rdquo;, BZip2Codec.class, CompressionCodec.class); Job job = Job.getInstance(configuration); job.setJarByClass(WordCountDriver.class); job.setMapperClass(WordCountMapper.class); job.setReducerClass(WordCountReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); boolean result = job.waitForCompletion(true); System.exit(result ? 1 : 0); } }</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <p>2．Mapper保持不变</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.compress; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class WordCountMapper extends Mapper\&lt;LongWritable, Text, Text, IntWritable>{ Text k = new Text(); IntWritable v = new IntWritable(1); \@Override protected void map(LongWritable key, Text value, Context context)throws IOException, InterruptedException { // 1 获取一行 String line = value.toString(); // 2 切割 String[] words = line.split(&rdquo; &ldquo;); // 3 循环写出 for(String word:words){ k.set(word); context.write(k, v); } } }</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <p>3．Reducer保持不变</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.compress; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class WordCountReducer extends Reducer\&lt;Text, IntWritable, Text, IntWritable>{ IntWritable v = new IntWritable(); \@Override protected void reduce(Text key, Iterable\&lt;IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; // 1 汇总 for(IntWritable value:values){ sum += value.get(); } v.set(sum); // 2 输出 context.write(key, v); } }</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <h3 id=463-reduce>4.6.3 Reduce输出端采用压缩</h3> <p>基于WordCount案例处理。</p> <p>1．修改驱动</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.compress; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.BZip2Codec; import org.apache.hadoop.io.compress.DefaultCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.io.compress.Lz4Codec; import org.apache.hadoop.io.compress.SnappyCodec; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class WordCountDriver { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { Configuration configuration = new Configuration(); Job job = Job.getInstance(configuration); job.setJarByClass(WordCountDriver.class); job.setMapperClass(WordCountMapper.class); job.setReducerClass(WordCountReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); // 设置reduce端输出压缩开启 FileOutputFormat.setCompressOutput(job, true); // 设置压缩的方式 FileOutputFormat.setOutputCompressorClass(job, BZip2Codec.class); // FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); // FileOutputFormat.setOutputCompressorClass(job, DefaultCodec.class); boolean result = job.waitForCompletion(true); System.exit(result?1:0); } }</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <p>2．Mapper和Reducer保持不变（详见4.6.2）</p> <h2 id=5-yarn>第5章 Yarn资源调度器</h2> <p>Yarn是一个资源调度平台，负责为运算程序提供服务器运算资源，相当于一个分布式的操作系统平台，而MapReduce等运算程序则相当于运行于操作系统之上的应用程序。</p> <h2 id=51-yarn>5.1 Yarn基本架构</h2> <p>YARN主要由ResourceManager、NodeManager、ApplicationMaster和Container等组件构成，如图4-23所示。</p> <p>图4-23 Yarn基本架构</p> <h2 id=53-yarn>5.3 Yarn工作机制</h2> <p>1．Yarn运行机制，如图4-24所示。</p> <p>图4-24 Yarn工作机制</p> <p>2．工作机制详解</p> <p>（1）MR程序提交到客户端所在的节点。</p> <p>（2）YarnRunner向ResourceManager申请一个Application。</p> <p>（3）RM将该应用程序的资源路径返回给YarnRunner。</p> <p>（4）该程序将运行所需资源提交到HDFS上。</p> <p>（5）程序资源提交完毕后，申请运行mrAppMaster。</p> <p>（6）RM将用户的请求初始化成一个Task。</p> <p>（7）其中一个NodeManager领取到Task任务。</p> <p>（8）该NodeManager创建容器Container，并产生MRAppmaster。</p> <p>（9）Container从HDFS上拷贝资源到本地。</p> <p>（10）MRAppmaster向RM 申请运行MapTask资源。</p> <p>（11）RM将运行MapTask任务分配给另外两个NodeManager，另两个NodeManager分别领取任务并创建容器。</p> <p>（12）MR向两个接收到任务的NodeManager发送程序启动脚本，这两个NodeManager分别启动MapTask，MapTask对数据分区排序。</p> <p>（13）MrAppMaster等待所有MapTask运行完毕后，向RM申请容器，运行ReduceTask。</p> <p>（14）ReduceTask向MapTask获取相应分区的数据。</p> <p>（15）程序运行完毕后，MR会向RM申请注销自己。</p> <h2 id=54>5.4 作业提交全过程</h2> <p>1．作业提交过程之YARN，如图4-25所示。</p> <p>图4-25 作业提交过程之Yarn</p> <p>作业提交全过程详解</p> <p>（1）作业提交</p> <p>第1步：Client调用job.waitForCompletion方法，向整个集群提交MapReduce作业。</p> <p>第2步：Client向RM申请一个作业id。</p> <p>第3步：RM给Client返回该job资源的提交路径和作业id。</p> <p>第4步：Client提交jar包、切片信息和配置文件到指定的资源提交路径。</p> <p>第5步：Client提交完资源后，向RM申请运行MrAppMaster。</p> <p>（2）作业初始化</p> <p>第6步：当RM收到Client的请求后，将该job添加到容量调度器中。</p> <p>第7步：某一个空闲的NM领取到该Job。</p> <p>第8步：该NM创建Container，并产生MRAppmaster。</p> <p>第9步：下载Client提交的资源到本地。</p> <p>（3）任务分配</p> <p>第10步：MrAppMaster向RM申请运行多个MapTask任务资源。</p> <p>第11步：RM将运行MapTask任务分配给另外两个NodeManager，另两个NodeManager分别领取任务并创建容器。</p> <p>（4）任务运行</p> <p>第12步：MR向两个接收到任务的NodeManager发送程序启动脚本，这两个NodeManager分别启动MapTask，MapTask对数据分区排序。</p> <p>第13步：MrAppMaster等待所有MapTask运行完毕后，向RM申请容器，运行ReduceTask。</p> <p>第14步：ReduceTask向MapTask获取相应分区的数据。</p> <p>第15步：程序运行完毕后，MR会向RM申请注销自己。</p> <p>（5）进度和状态更新</p> <p>YARN中的任务将其进度和状态(包括counter)返回给应用管理器, 客户端每秒(通过mapreduce.client.progressmonitor.pollinterval设置)向应用管理器请求进度更新, 展示给用户。</p> <p>（6）作业完成</p> <p>除了向应用管理器请求作业进度外, 客户端每5秒都会通过调用waitForCompletion()来检查作业是否完成。时间间隔可以通过mapreduce.client.completion.pollinterval来设置。作业完成之后, 应用管理器和Container会清理工作状态。作业的信息会被作业历史服务器存储以备之后用户核查。</p> <p>2．作业提交过程之MapReduce，如图4-26所示</p> <p>图4-26 作业提交过程之MapReduce</p> <h2 id=55>5.5 资源调度器</h2> <p>目前，Hadoop作业调度器主要有三种：FIFO、Capacity Scheduler和Fair Scheduler。Hadoop2.7.2默认的资源调度器是Capacity Scheduler。</p> <p>具体设置详见：yarn-default.xml文件</p> <blockquote> <p>\&lt;property></p> <p>\&lt;description>The class to use as the resource scheduler.\&lt;/description></p> <p>\&lt;name>yarn.resourcemanager.scheduler.class\&lt;/name></p> <p>\&lt;value>org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler\&lt;/value></p> <p>\&lt;/property></p> </blockquote> <p>1．先进先出调度器（FIFO），如图4-27所示</p> <p>图4-27 FIFO调度器</p> <p>2．容量调度器（Capacity Scheduler），如图4-28所示</p> <p>图4-28容量调度器</p> <p>3．公平调度器（Fair Scheduler），如图4-29所示</p> <p>图4-29公平调度器</p> <h2 id=56>5.6 任务的推测执行</h2> <p>1．作业完成时间取决于最慢的任务完成时间</p> <p>一个作业由若干个Map任务和Reduce任务构成。因硬件老化、软件Bug等，某些任务可能运行非常慢。</p> <p>思考：系统中有99%的Map任务都完成了，只有少数几个Map老是进度很慢，完不成，怎么办？</p> <p>2．推测执行机制</p> <p>发现拖后腿的任务，比如某个任务运行速度远慢于任务平均速度。为拖后腿任务启动一个备份任务，同时运行。谁先运行完，则采用谁的结果。</p> <p>3．执行推测任务的前提条件</p> <p>（1）每个Task只能有一个备份任务</p> <p>（2）当前Job已完成的Task必须不小于0.05（5%）</p> <p>（3）开启推测执行参数设置。mapred-site.xml文件中默认是打开的。</p> <blockquote> <p>\&lt;property></p> <p>\&lt;name>mapreduce.map.speculative\&lt;/name></p> <p>\&lt;value>true\&lt;/value></p> <p>\&lt;description>If true, then multiple instances of some map tasks may be executed in parallel.\&lt;/description></p> <p>\&lt;/property></p> <p>\&lt;property></p> <p>\&lt;name>mapreduce.reduce.speculative\&lt;/name></p> <p>\&lt;value>true\&lt;/value></p> <p>\&lt;description>If true, then multiple instances of some reduce tasks may be executed in parallel.\&lt;/description></p> <p>\&lt;/property></p> </blockquote> <p>4．不能启用推测执行机制情况</p> <p>（1）任务间存在严重的负载倾斜。</p> <p>（2）特殊任务，比如任务向数据库中写数据。</p> <p>5．算法原理，如图4-20所示</p> <p>图4-30 推测执行算法原理</p> <h2 id=6-hadoop>第6章 Hadoop企业优化</h2> <h2 id=61-mapreduce>6.1 MapReduce 跑的慢的原因</h2> <h2 id=62-mapreduce>6.2 MapReduce优化方法</h2> <p>MapReduce优化方法主要从六个方面考虑：数据输入、Map阶段、Reduce阶段、IO传输、数据倾斜问题和常用的调优参数。</p> <h3 id=621>6.2.1 数据输入</h3> <h3 id=622-map>6.2.2 Map阶段</h3> <h3 id=623-reduce>6.2.3 Reduce阶段</h3> <h3 id=624-io>6.2.4 I/O传输</h3> <h3 id=625>6.2.5 数据倾斜问题</h3> <h3 id=626>6.2.6 常用的调优参数</h3> <p>1．资源相关参数</p> <p>（1）以下参数是在用户自己的MR应用程序中配置就可以生效（mapred-default.xml）</p> <p>表4-12</p> <table> <thead> <tr> <th>配置参数</th> <th>参数说明</th> </tr> </thead> <tbody> <tr> <td>mapreduce.map.memory.mb</td> <td>一个MapTask可使用的资源上限（单位:MB），默认为1024。如果MapTask实际使用的资源量超过该值，则会被强制杀死。</td> </tr> <tr> <td>mapreduce.reduce.memory.mb</td> <td>一个ReduceTask可使用的资源上限（单位:MB），默认为1024。如果ReduceTask实际使用的资源量超过该值，则会被强制杀死。</td> </tr> <tr> <td>mapreduce.map.cpu.vcores</td> <td>每个MapTask可使用的最多cpu core数目，默认值: 1</td> </tr> <tr> <td>mapreduce.reduce.cpu.vcores</td> <td>每个ReduceTask可使用的最多cpu core数目，默认值: 1</td> </tr> <tr> <td>mapreduce.reduce.shuffle.parallelcopies</td> <td>每个Reduce去Map中取数据的并行数。默认值是5</td> </tr> <tr> <td>mapreduce.reduce.shuffle.merge.percent</td> <td>Buffer中的数据达到多少比例开始写入磁盘。默认值0.66</td> </tr> <tr> <td>mapreduce.reduce.shuffle.input.buffer.percent</td> <td>Buffer大小占Reduce可用内存的比例。默认值0.7</td> </tr> <tr> <td>mapreduce.reduce.input.buffer.percent</td> <td>指定多少比例的内存用来存放Buffer中的数据，默认值是0.0</td> </tr> </tbody> </table> <blockquote> <p>（2）应该在YARN启动之前就配置在服务器的配置文件中才能生效（yarn-default.xml）</p> </blockquote> <p>表4-13</p> <table> <thead> <tr> <th>配置参数</th> <th>参数说明</th> </tr> </thead> <tbody> <tr> <td>yarn.scheduler.minimum-allocation-mb</td> <td>给应用程序Container分配的最小内存，默认值：1024</td> </tr> <tr> <td>yarn.scheduler.maximum-allocation-mb</td> <td>给应用程序Container分配的最大内存，默认值：8192</td> </tr> <tr> <td>yarn.scheduler.minimum-allocation-vcores</td> <td>每个Container申请的最小CPU核数，默认值：1</td> </tr> <tr> <td>yarn.scheduler.maximum-allocation-vcores</td> <td>每个Container申请的最大CPU核数，默认值：32</td> </tr> <tr> <td>yarn.nodemanager.resource.memory-mb</td> <td>给Containers分配的最大物理内存，默认值：8192</td> </tr> </tbody> </table> <p>（3）Shuffle性能优化的关键参数，应在YARN启动之前就配置好（mapred-default.xml）</p> <blockquote> <p>表4-14</p> </blockquote> <table> <thead> <tr> <th>配置参数</th> <th>参数说明</th> </tr> </thead> <tbody> <tr> <td>mapreduce.task.io.sort.mb</td> <td>Shuffle的环形缓冲区大小，默认100m</td> </tr> <tr> <td>mapreduce.map.sort.spill.percent</td> <td>环形缓冲区溢出的阈值，默认80%</td> </tr> </tbody> </table> <p>2．容错相关参数(MapReduce性能优化)</p> <p>表4-15</p> <table> <thead> <tr> <th>配置参数</th> <th>参数说明</th> </tr> </thead> <tbody> <tr> <td>mapreduce.map.maxattempts</td> <td>每个Map Task最大重试次数，一旦重试参数超过该值，则认为Map Task运行失败，默认值：4。</td> </tr> <tr> <td>mapreduce.reduce.maxattempts</td> <td>每个Reduce Task最大重试次数，一旦重试参数超过该值，则认为Map Task运行失败，默认值：4。</td> </tr> <tr> <td>mapreduce.task.timeout</td> <td>Task超时时间，经常需要设置的一个参数，该参数表达的意思为：如果一个Task在一定时间内没有任何进入，即不会读取新的数据，也没有输出数据，则认为该Task处于Block状态，可能是卡住了，也许永远会卡住，为了防止因为用户程序永远Block住不退出，则强制设置了一个该超时时间（单位毫秒），默认是600000。如果你的程序对每条输入数据的处理时间过长（比如会访问数据库，通过网络拉取数据等），建议将该参数调大，该参数过小常出现的错误提示是“AttemptID:attempt_14267829456721_123456_m_000224_0 Timed out after 300 secsContainer killed by the ApplicationMaster.”。</td> </tr> </tbody> </table> <h2 id=63-hdfs>6.3 HDFS小文件优化方法</h2> <h3 id=631-hdfs>6.3.1 HDFS小文件弊端</h3> <p>HDFS上每个文件都要在NameNode上建立一个索引，这个索引的大小约为150byte，这样当小文件比较多的时候，就会产生很多的索引文件，一方面会大量占用NameNode的内存空间，另一方面就是索引文件过大使得索引速度变慢。</p> <h3 id=632-hdfs>6.3.2 HDFS小文件解决方案</h3> <p>小文件的优化无非以下几种方式：</p> <p>（1）在数据采集的时候，就将小文件或小批数据合成大文件再上传HDFS。</p> <p>（2）在业务处理之前，在HDFS上使用MapReduce程序对小文件进行合并。</p> <p>（3）在MapReduce处理时，可采用CombineTextInputFormat提高效率。</p> <h2 id=7-mapreduce>第7章 MapReduce扩展案例</h2> <h2 id=71-job>7.1 倒排索引案例（多job串联）</h2> <p>1．需求</p> <p>有大量的文本（文档、网页），需要建立搜索索引，如图4-31所示。</p> <p>（1）数据输入</p> <p>（2）期望输出数据</p> <blockquote> <p>atguigu c.txt&ndash;>2 b.txt&ndash;>2 a.txt&ndash;>3</p> <p>pingping c.txt&ndash;>1 b.txt&ndash;>3 a.txt&ndash;>1</p> <p>ss c.txt&ndash;>1 b.txt&ndash;>1 a.txt&ndash;>2</p> </blockquote> <p>2．需求分析</p> <p>3．第一次处理</p> <p>（1）第一次处理，编写OneIndexMapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.index;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.IntWritable;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileSplit;</p> <p>public class OneIndexMapper extends Mapper\&lt;LongWritable, Text, Text, IntWritable>{</p> <p>String name;</p> <p>Text k = new Text();</p> <p>IntWritable v = new IntWritable();</p> <p>\@Override</p> <p>protected void setup(Context context)throws IOException, InterruptedException {</p> <p>// 获取文件名称</p> <p>FileSplit split = (FileSplit) context.getInputSplit();</p> <p>name = split.getPath().getName();</p> <p>}</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取1行</p> <p>String line = value.toString();</p> <p>// 2 切割</p> <p>String[] fields = line.split(&rdquo; &ldquo;);</p> <p>for (String word : fields) {</p> <p>// 3 拼接</p> <p>k.set(word+&rdquo;&ndash;&ldquo;+name);</p> <p>v.set(1);</p> <p>// 4 写出</p> <p>context.write(k, v);</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>（2）第一次处理，编写OneIndexReducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.index;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.IntWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class OneIndexReducer extends Reducer\&lt;Text, IntWritable, Text, IntWritable>{</p> <p>IntWritable v = new IntWritable();</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;IntWritable> values,Context context) throws IOException, InterruptedException {</p> <p>int sum = 0;</p> <p>// 1 累加求和</p> <p>for(IntWritable value: values){</p> <p>sum +=value.get();</p> <p>}</p> <p>v.set(sum);</p> <p>// 2 写出</p> <p>context.write(key, v);</p> <p>}</p> <p>}</p> </blockquote> <p>（3）第一次处理，编写OneIndexDriver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.index;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.IntWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class OneIndexDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[] { &ldquo;e:/input/inputoneindex&rdquo;, &ldquo;e:/output5&rdquo; };</p> <p>Configuration conf = new Configuration();</p> <p>Job job = Job.getInstance(conf);</p> <p>job.setJarByClass(OneIndexDriver.class);</p> <p>job.setMapperClass(OneIndexMapper.class);</p> <p>job.setReducerClass(OneIndexReducer.class);</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(IntWritable.class);</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(IntWritable.class);</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>job.waitForCompletion(true);</p> <p>}</p> <p>}</p> </blockquote> <p>（4）查看第一次输出结果</p> <table> <thead> <tr> <th>atguigu&ndash;a.txt 3</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>atguigu&ndash;b.txt 2</p> <p>atguigu&ndash;c.txt 2</p> <p>pingping&ndash;a.txt 1</p> <p>pingping&ndash;b.txt 3</p> <p>pingping&ndash;c.txt 1</p> <p>ss&ndash;a.txt 2</p> <p>ss&ndash;b.txt 1</p> <p>ss&ndash;c.txt 1</p> </blockquote> <p>4．第二次处理</p> <p>（1）第二次处理，编写TwoIndexMapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.index;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class TwoIndexMapper extends Mapper\&lt;LongWritable, Text, Text, Text>{</p> <p>Text k = new Text();</p> <p>Text v = new Text();</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>// 1 获取1行数据</p> <p>String line = value.toString();</p> <p>// 2用“&ndash;”切割</p> <p>String[] fields = line.split(&ldquo;&ndash;&ldquo;);</p> <p>k.set(fields[0]);</p> <p>v.set(fields[1]);</p> <p>// 3 输出数据</p> <p>context.write(k, v);</p> <p>}</p> <p>}</p> </blockquote> <p>（2）第二次处理，编写TwoIndexReducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.index;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class TwoIndexReducer extends Reducer\&lt;Text, Text, Text, Text> {</p> <p>Text v = new Text();</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;Text> values, Context context) throws IOException, InterruptedException {</p> <p>// atguigu a.txt 3</p> <p>// atguigu b.txt 2</p> <p>// atguigu c.txt 2</p> <p>// atguigu c.txt&ndash;>2 b.txt&ndash;>2 a.txt&ndash;>3</p> <p>StringBuilder sb = new StringBuilder();</p> <p>// 1 拼接</p> <p>for (Text value : values) {</p> <p>sb.append(value.toString().replace(&ldquo;\t&rdquo;, &ldquo;&ndash;>&ldquo;) + &ldquo;\t&rdquo;);</p> <p>}</p> <p>v.set(sb.toString());</p> <p>// 2 写出</p> <p>context.write(key, v);</p> <p>}</p> <p>}</p> </blockquote> <p>（3）第二次处理，编写TwoIndexDriver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.index;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class TwoIndexDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>// 输入输出路径需要根据自己电脑上实际的输入输出路径设置</p> <p>args = new String[] { &ldquo;e:/input/inputtwoindex&rdquo;, &ldquo;e:/output6&rdquo; };</p> <p>Configuration config = new Configuration();</p> <p>Job job = Job.getInstance(config);</p> <p>job.setJarByClass(TwoIndexDriver.class);</p> <p>job.setMapperClass(TwoIndexMapper.class);</p> <p>job.setReducerClass(TwoIndexReducer.class);</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(Text.class);</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(Text.class);</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result?0:1);</p> <p>}</p> <p>}</p> </blockquote> <p>（4）第二次查看最终结果</p> <blockquote> <p>atguigu c.txt&ndash;>2 b.txt&ndash;>2 a.txt&ndash;>3</p> <p>pingping c.txt&ndash;>1 b.txt&ndash;>3 a.txt&ndash;>1</p> <p>ss c.txt&ndash;>1 b.txt&ndash;>1 a.txt&ndash;>2</p> </blockquote> <h2 id=72-topn>7.2 TopN案例</h2> <p>1．需求</p> <p>对需求2.3输出结果进行加工，输出流量使用量在前10的用户信息</p> <p>（1）输入数据 （2）输出数据</p> <p>2．需求分析</p> <p>3．实现代码</p> <p>（1）编写FlowBean类</p> <table> <thead> <tr> <th>package com.atguigu.mr.top;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.DataInput;</p> <p>import java.io.DataOutput;</p> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.WritableComparable;</p> <p>public class FlowBean implements WritableComparable\&lt;FlowBean>{</p> <p>private long upFlow;</p> <p>private long downFlow;</p> <p>private long sumFlow;</p> <p>public FlowBean() {</p> <p>super();</p> <p>}</p> <p>public FlowBean(long upFlow, long downFlow) {</p> <p>super();</p> <p>this.upFlow = upFlow;</p> <p>this.downFlow = downFlow;</p> <p>}</p> <p>\@Override</p> <p>public void write(DataOutput out) throws IOException {</p> <p>out.writeLong(upFlow);</p> <p>out.writeLong(downFlow);</p> <p>out.writeLong(sumFlow);</p> <p>}</p> <p>\@Override</p> <p>public void readFields(DataInput in) throws IOException {</p> <p>upFlow = in.readLong();</p> <p>downFlow = in.readLong();</p> <p>sumFlow = in.readLong();</p> <p>}</p> <p>public long getUpFlow() {</p> <p>return upFlow;</p> <p>}</p> <p>public void setUpFlow(long upFlow) {</p> <p>this.upFlow = upFlow;</p> <p>}</p> <p>public long getDownFlow() {</p> <p>return downFlow;</p> <p>}</p> <p>public void setDownFlow(long downFlow) {</p> <p>this.downFlow = downFlow;</p> <p>}</p> <p>public long getSumFlow() {</p> <p>return sumFlow;</p> <p>}</p> <p>public void setSumFlow(long sumFlow) {</p> <p>this.sumFlow = sumFlow;</p> <p>}</p> <p>\@Override</p> <p>public String toString() {</p> <p>return upFlow + &ldquo;\t&rdquo; + downFlow + &ldquo;\t&rdquo; + sumFlow;</p> <p>}</p> <p>public void set(long downFlow2, long upFlow2) {</p> <p>downFlow = downFlow2;</p> <p>upFlow = upFlow2;</p> <p>sumFlow = downFlow2 + upFlow2;</p> <p>}</p> <p>\@Override</p> <p>public int compareTo(FlowBean bean) {</p> <p>int result;</p> <p>if (this.sumFlow > bean.getSumFlow()) {</p> <p>result = -1;</p> <p>}else if (this.sumFlow \&lt; bean.getSumFlow()) {</p> <p>result = 1;</p> <p>}else {</p> <p>result = 0;</p> <p>}</p> <p>return result;</p> <p>}</p> <p>}</p> </blockquote> <p>（2）编写TopNMapper类</p> <table> <thead> <tr> <th>package com.atguigu.mr.top;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import java.util.Iterator;</p> <p>import java.util.TreeMap;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class TopNMapper extends Mapper\&lt;LongWritable, Text, FlowBean, Text>{</p> <p>// 定义一个TreeMap作为存储数据的容器（天然按key排序）</p> <p>private TreeMap\&lt;FlowBean, Text> flowMap = new TreeMap\&lt;FlowBean, Text>();</p> <p>private FlowBean kBean;</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {</p> <p>kBean = new FlowBean();</p> <p>Text v = new Text();</p> <p>// 1 获取一行</p> <p>String line = value.toString();</p> <p>// 2 切割</p> <p>String[] fields = line.split(&ldquo;\t&rdquo;);</p> <p>// 3 封装数据</p> <p>String phoneNum = fields[0];</p> <p>long upFlow = Long.parseLong(fields[1]);</p> <p>long downFlow = Long.parseLong(fields[2]);</p> <p>long sumFlow = Long.parseLong(fields[3]);</p> <p>kBean.setDownFlow(downFlow);</p> <p>kBean.setUpFlow(upFlow);</p> <p>kBean.setSumFlow(sumFlow);</p> <p>v.set(phoneNum);</p> <p>// 4 向TreeMap中添加数据</p> <p>flowMap.put(kBean, v);</p> <p>// 5 限制TreeMap的数据量，超过10条就删除掉流量最小的一条数据</p> <p>if (flowMap.size() > 10) {</p> <p>// flowMap.remove(flowMap.firstKey());</p> <p>flowMap.remove(flowMap.lastKey());</p> <p>}</p> <p>}</p> <p>\@Override</p> <p>protected void cleanup(Context context) throws IOException, InterruptedException {</p> <p>// 6 遍历treeMap集合，输出数据</p> <p>Iterator\&lt;FlowBean> bean = flowMap.keySet().iterator();</p> <p>while (bean.hasNext()) {</p> <p>FlowBean k = bean.next();</p> <p>context.write(k, flowMap.get(k));</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>（3）编写TopNReducer类</p> <table> <thead> <tr> <th>package com.atguigu.mr.top;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import java.util.Iterator;</p> <p>import java.util.TreeMap;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class TopNReducer extends Reducer\&lt;FlowBean, Text, Text, FlowBean> {</p> <p>// 定义一个TreeMap作为存储数据的容器（天然按key排序）</p> <p>TreeMap\&lt;FlowBean, Text> flowMap = new TreeMap\&lt;FlowBean, Text>();</p> <p>\@Override</p> <p>protected void reduce(FlowBean key, Iterable\&lt;Text> values, Context context)throws IOException, InterruptedException {</p> <p>for (Text value : values) {</p> <p>FlowBean bean = new FlowBean();</p> <p>bean.set(key.getDownFlow(), key.getUpFlow());</p> <p>// 1 向treeMap集合中添加数据</p> <p>flowMap.put(bean, new Text(value));</p> <p>// 2 限制TreeMap数据量，超过10条就删除掉流量最小的一条数据</p> <p>if (flowMap.size() > 10) {</p> <p>// flowMap.remove(flowMap.firstKey());</p> <p>flowMap.remove(flowMap.lastKey());</p> <p>}</p> <p>}</p> <p>}</p> <p>\@Override</p> <p>protected void cleanup(Reducer\&lt;FlowBean, Text, Text, FlowBean>.Context context) throws IOException, InterruptedException {</p> <p>// 3 遍历集合，输出数据</p> <p>Iterator\&lt;FlowBean> it = flowMap.keySet().iterator();</p> <p>while (it.hasNext()) {</p> <p>FlowBean v = it.next();</p> <p>context.write(new Text(flowMap.get(v)), v);</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>（4）编写TopNDriver类</p> <blockquote> <p>package com.atguigu.mr.top;</p> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class TopNDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>args = new String[]{&ldquo;e:/output1&rdquo;,&rdquo;e:/output3&rdquo;};</p> <p>// 1 获取配置信息，或者job对象实例</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 6 指定本程序的jar包所在的本地路径</p> <p>job.setJarByClass(TopNDriver.class);</p> <p>// 2 指定本业务job要使用的mapper/Reducer业务类</p> <p>job.setMapperClass(TopNMapper.class);</p> <p>job.setReducerClass(TopNReducer.class);</p> <p>// 3 指定mapper输出数据的kv类型</p> <p>job.setMapOutputKeyClass(FlowBean.class);</p> <p>job.setMapOutputValueClass(Text.class);</p> <p>// 4 指定最终输出的数据的kv类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(FlowBean.class);</p> <p>// 5 指定job的输入原始文件所在目录</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 7 将job中配置的相关参数，以及job所用的java类所在的jar包， 提交给yarn去运行</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result ? 0 : 1);</p> <p>}</p> <p>}</p> </blockquote> <h2 id=73>7.3 找博客共同好友案例</h2> <p>1．需求</p> <p>以下是博客的好友列表数据，冒号前是一个用户，冒号后是该用户的所有好友（数据中的好友关系是单向的）</p> <p>求出哪些人两两之间有共同好友，及他俩的共同好友都有谁？</p> <p>（1）数据输入</p> <p>2．需求分析</p> <p>先求出A、B、C、….等是谁的好友</p> <p>第一次输出结果</p> <table> <thead> <tr> <th>A I,K,C,B,G,F,H,O,D,</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>B A,F,J,E,</p> <p>C A,E,B,H,F,G,K,</p> <p>D G,C,K,A,L,F,E,H,</p> <p>E G,M,L,H,A,F,B,D,</p> <p>F L,M,D,C,G,A,</p> <p>G M,</p> <p>H O,</p> <p>I O,C,</p> <p>J O,</p> <p>K B,</p> <p>L D,E,</p> <p>M E,F,</p> <p>O A,H,I,J,F,</p> </blockquote> <p>第二次输出结果</p> <table> <thead> <tr> <th>A-B E C</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>A-C D F</p> <p>A-D E F</p> <p>A-E D B C</p> <p>A-F O B C D E</p> <p>A-G F E C D</p> <p>A-H E C D O</p> <p>A-I O</p> <p>A-J O B</p> <p>A-K D C</p> <p>A-L F E D</p> <p>A-M E F</p> <p>B-C A</p> <p>B-D A E</p> <p>B-E C</p> <p>B-F E A C</p> <p>B-G C E A</p> <p>B-H A E C</p> <p>B-I A</p> <p>B-K C A</p> <p>B-L E</p> <p>B-M E</p> <p>B-O A</p> <p>C-D A F</p> <p>C-E D</p> <p>C-F D A</p> <p>C-G D F A</p> <p>C-H D A</p> <p>C-I A</p> <p>C-K A D</p> <p>C-L D F</p> <p>C-M F</p> <p>C-O I A</p> <p>D-E L</p> <p>D-F A E</p> <p>D-G E A F</p> <p>D-H A E</p> <p>D-I A</p> <p>D-K A</p> <p>D-L E F</p> <p>D-M F E</p> <p>D-O A</p> <p>E-F D M C B</p> <p>E-G C D</p> <p>E-H C D</p> <p>E-J B</p> <p>E-K C D</p> <p>E-L D</p> <p>F-G D C A E</p> <p>F-H A D O E C</p> <p>F-I O A</p> <p>F-J B O</p> <p>F-K D C A</p> <p>F-L E D</p> <p>F-M E</p> <p>F-O A</p> <p>G-H D C E A</p> <p>G-I A</p> <p>G-K D A C</p> <p>G-L D F E</p> <p>G-M E F</p> <p>G-O A</p> <p>H-I O A</p> <p>H-J O</p> <p>H-K A C D</p> <p>H-L D E</p> <p>H-M E</p> <p>H-O A</p> <p>I-J O</p> <p>I-K A</p> <p>I-O A</p> <p>K-L D</p> <p>K-O A</p> <p>L-M E F</p> </blockquote> <p>3．代码实现</p> <p>（1）第一次Mapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.friends;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class OneShareFriendsMapper extends Mapper\&lt;LongWritable, Text, Text, Text>{</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Mapper\&lt;LongWritable, Text, Text, Text>.Context context)</p> <p>throws IOException, InterruptedException {</p> <p>// 1 获取一行 A:B,C,D,F,E,O</p> <p>String line = value.toString();</p> <p>// 2 切割</p> <p>String[] fields = line.split(&ldquo;:&rdquo;);</p> <p>// 3 获取person和好友</p> <p>String person = fields[0];</p> <p>String[] friends = fields[1].split(&ldquo;,&rdquo;);</p> <p>// 4写出去</p> <p>for(String friend: friends){</p> <p>// 输出 \&lt;好友，人></p> <p>context.write(new Text(friend), new Text(person));</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>（2）第一次Reducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.friends;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class OneShareFriendsReducer extends Reducer\&lt;Text, Text, Text, Text>{</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;Text> values, Context context)throws IOException, InterruptedException {</p> <p>StringBuffer sb = new StringBuffer();</p> <p>//1 拼接</p> <p>for(Text person: values){</p> <p>sb.append(person).append(&ldquo;,&rdquo;);</p> <p>}</p> <p>//2 写出</p> <p>context.write(key, new Text(sb.toString()));</p> <p>}</p> <p>}</p> </blockquote> <p>（3）第一次Driver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.friends;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class OneShareFriendsDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>// 1 获取job对象</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 2 指定jar包运行的路径</p> <p>job.setJarByClass(OneShareFriendsDriver.class);</p> <p>// 3 指定map/reduce使用的类</p> <p>job.setMapperClass(OneShareFriendsMapper.class);</p> <p>job.setReducerClass(OneShareFriendsReducer.class);</p> <p>// 4 指定map输出的数据类型</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(Text.class);</p> <p>// 5 指定最终输出的数据类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(Text.class);</p> <p>// 6 指定job的输入原始所在目录</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 7 提交</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result?0:1);</p> <p>}</p> <p>}</p> </blockquote> <p>（4）第二次Mapper类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.friends;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import java.util.Arrays;</p> <p>import org.apache.hadoop.io.LongWritable;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Mapper;</p> <p>public class TwoShareFriendsMapper extends Mapper\&lt;LongWritable, Text, Text, Text>{</p> <p>\@Override</p> <p>protected void map(LongWritable key, Text value, Context context)</p> <p>throws IOException, InterruptedException {</p> <p>// A I,K,C,B,G,F,H,O,D,</p> <p>// 友 人，人，人</p> <p>String line = value.toString();</p> <p>String[] friend_persons = line.split(&ldquo;\t&rdquo;);</p> <p>String friend = friend_persons[0];</p> <p>String[] persons = friend_persons[1].split(&ldquo;,&rdquo;);</p> <p>Arrays.sort(persons);</p> <p>for (int i = 0; i \&lt; persons.length - 1; i++) {</p> <p>for (int j = i + 1; j \&lt; persons.length; j++) {</p> <p>// 发出 \&lt;人-人，好友> ，这样，相同的“人-人”对的所有好友就会到同1个reduce中去</p> <p>context.write(new Text(persons[i] + &ldquo;-&rdquo; + persons[j]), new Text(friend));</p> <p>}</p> <p>}</p> <p>}</p> <p>}</p> </blockquote> <p>（5）第二次Reducer类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.friends;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import java.io.IOException;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Reducer;</p> <p>public class TwoShareFriendsReducer extends Reducer\&lt;Text, Text, Text, Text>{</p> <p>\@Override</p> <p>protected void reduce(Text key, Iterable\&lt;Text> values, Context context) throws IOException, InterruptedException {</p> <p>StringBuffer sb = new StringBuffer();</p> <p>for (Text friend : values) {</p> <p>sb.append(friend).append(&rdquo; &ldquo;);</p> <p>}</p> <p>context.write(key, new Text(sb.toString()));</p> <p>}</p> <p>}</p> </blockquote> <p>（6）第二次Driver类</p> <table> <thead> <tr> <th>package com.atguigu.mapreduce.friends;</th> </tr> </thead> <tbody> <tr> <td></td> </tr> </tbody> </table> <blockquote> <p>import org.apache.hadoop.conf.Configuration;</p> <p>import org.apache.hadoop.fs.Path;</p> <p>import org.apache.hadoop.io.Text;</p> <p>import org.apache.hadoop.mapreduce.Job;</p> <p>import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;</p> <p>import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;</p> <p>public class TwoShareFriendsDriver {</p> <p>public static void main(String[] args) throws Exception {</p> <p>// 1 获取job对象</p> <p>Configuration configuration = new Configuration();</p> <p>Job job = Job.getInstance(configuration);</p> <p>// 2 指定jar包运行的路径</p> <p>job.setJarByClass(TwoShareFriendsDriver.class);</p> <p>// 3 指定map/reduce使用的类</p> <p>job.setMapperClass(TwoShareFriendsMapper.class);</p> <p>job.setReducerClass(TwoShareFriendsReducer.class);</p> <p>// 4 指定map输出的数据类型</p> <p>job.setMapOutputKeyClass(Text.class);</p> <p>job.setMapOutputValueClass(Text.class);</p> <p>// 5 指定最终输出的数据类型</p> <p>job.setOutputKeyClass(Text.class);</p> <p>job.setOutputValueClass(Text.class);</p> <p>// 6 指定job的输入原始所在目录</p> <p>FileInputFormat.setInputPaths(job, new Path(args[0]));</p> <p>FileOutputFormat.setOutputPath(job, new Path(args[1]));</p> <p>// 7 提交</p> <p>boolean result = job.waitForCompletion(true);</p> <p>System.exit(result?0:1);</p> <p>}</p> <p>}</p> </blockquote> <h2 id=8>第8章 常见错误及解决方案</h2> <p>1）导包容易出错。尤其Text和CombineTextInputFormat。</p> <p>2）Mapper中第一个输入的参数必须是LongWritable或者NullWritable，不可以是IntWritable. 报的错误是类型转换异常。</p> <p>3）java.lang.Exception: java.io.IOException: Illegal partition for 13926435656 (4)，说明Partition和ReduceTask个数没对上，调整ReduceTask个数。</p> <p>4）如果分区数不是1，但是reducetask为1，是否执行分区过程。答案是：不执行分区过程。因为在MapTask的源码中，执行分区的前提是先判断ReduceNum个数是否大于1。不大于1肯定不执行。</p> <p>5）在Windows环境编译的jar包导入到Linux环境中运行，</p> <p>hadoop jar wc.jar com.atguigu.mapreduce.wordcount.WordCountDriver /user/atguigu/ /user/atguigu/output</p> <p>报如下错误：</p> <p>Exception in thread &ldquo;main&rdquo; java.lang.UnsupportedClassVersionError: com/atguigu/mapreduce/wordcount/WordCountDriver : Unsupported major.minor version 52.0</p> <p>原因是Windows环境用的jdk1.7，Linux环境用的jdk1.8。</p> <p>解决方案：统一jdk版本。</p> <p>6）缓存pd.txt小文件案例中，报找不到pd.txt文件</p> <p>原因：大部分为路径书写错误。还有就是要检查pd.txt.txt的问题。还有个别电脑写相对路径找不到pd.txt，可以修改为绝对路径。</p> <p>7）报类型转换异常。</p> <p>通常都是在驱动函数中设置Map输出和最终输出时编写错误。</p> <p>Map输出的key如果没有排序，也会报类型转换异常。</p> <p>8）集群中运行wc.jar时出现了无法获得输入文件。</p> <p>原因：WordCount案例的输入文件不能放用HDFS集群的根目录。</p> <p>9）出现了如下相关异常</p> <p>Exception in thread &ldquo;main&rdquo; java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z</p> <p>at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)</p> <p>at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:609)</p> <p>at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:977)</p> <p>java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries.</p> <p>at org.apache.hadoop.util.Shell.getQualifiedBinPath(Shell.java:356)</p> <p>at org.apache.hadoop.util.Shell.getWinUtilsPath(Shell.java:371)</p> <p>at org.apache.hadoop.util.Shell.\&lt;clinit>(Shell.java:364)</p> <p>解决方案：拷贝hadoop.dll文件到Windows目录C:\Windows\System32。个别同学电脑还需要修改Hadoop源码。</p> <p>方案二：创建如下包名，并将NativeIO.java拷贝到该包名下</p> <p><img alt=C:\Users\Administrator\AppData\Roaming\feiq\RichOle\1212195040.bmp src=d4ce9fb85643d13fb575850e9e852ab0.png></p> <p>10）自定义Outputformat时，注意在RecordWirter中的close方法必须关闭流资源。否则输出的文件内容中数据为空。</p> <p>\@Override</p> <p>public void close(TaskAttemptContext context) throws IOException, InterruptedException {</p> <p>if (atguigufos != null) {</p> <p>atguigufos.close();</p> <p>}</p> <p>if (otherfos != null) {</p> <p>otherfos.close();</p> <p>}</p> <p>}</p> </article> </div> </div> </main> <footer class=md-footer> <div class=md-footer-nav> <nav class="md-footer-nav__inner md-grid" aria-label=Footer> <a href=../Hadoop-HDFS/ title=HDFS class="md-footer-nav__link md-footer-nav__link--prev" rel=prev> <div class="md-footer-nav__button md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11h12z"/></svg> </div> <div class=md-footer-nav__title> <div class=md-ellipsis> <span class=md-footer-nav__direction> 上一页 </span> HDFS </div> </div> </a> <a href=../Spark%E5%9F%BA%E7%A1%80/ title=Spark基础 class="md-footer-nav__link md-footer-nav__link--next" rel=next> <div class=md-footer-nav__title> <div class=md-ellipsis> <span class=md-footer-nav__direction> 下一页 </span> Spark基础 </div> </div> <div class="md-footer-nav__button md-icon"> <svg xmlns=http://www.w3.org/2000/svg viewbox="0 0 24 24"><path d="M4 11v2h12l-5.5 5.5 1.42 1.42L19.84 12l-7.92-7.92L10.5 5.5 16 11H4z"/></svg> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class=md-footer-copyright> <div class=md-footer-copyright__highlight> Copyright &copy; 2018 - 2029 Dayet 296577630@qq.com </div> Made with <a href=https://squidfunk.github.io/mkdocs-material/ target=_blank rel=noopener> Material for MkDocs </a> </div> </div> </div> </footer> </div> <script src=../../assets/javascripts/vendor.2d1db4bd.min.js></script> <script src=../../assets/javascripts/bundle.6627ddf3.min.js></script><script id=__lang type=application/json>{"clipboard.copy": "\u590d\u5236", "clipboard.copied": "\u5df2\u590d\u5236", "search.config.lang": "ja", "search.config.pipeline": "trimmer, stemmer", "search.config.separator": "[\\uff0c\\u3002]+", "search.result.placeholder": "\u952e\u5165\u4ee5\u5f00\u59cb\u641c\u7d22", "search.result.none": "\u6ca1\u6709\u627e\u5230\u7b26\u5408\u6761\u4ef6\u7684\u7ed3\u679c", "search.result.one": "\u627e\u5230 1 \u4e2a\u7b26\u5408\u6761\u4ef6\u7684\u7ed3\u679c", "search.result.other": "# \u4e2a\u7b26\u5408\u6761\u4ef6\u7684\u7ed3\u679c"}</script> <script>
        app = initialize({
          base: "../..",
          features: [],
          search: Object.assign({
            worker: "../../assets/javascripts/worker/search.5eca75d3.min.js"
          }, typeof search !== "undefined" && search)
        })
      </script> </body> </html>